zoukankan      html  css  js  c++  java
  • leetcode79 Word Search

    Given a 2D board and a word, find if the word exists in the grid.

    The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.

    For example,
    Given board =

    [
      ['A','B','C','E'],
      ['S','F','C','S'],
      ['A','D','E','E']
    ]
    

    word = "ABCCED", -> returns true,
    word = "SEE", -> returns true,
    word = "ABCB", -> returns false.

     1 class Solution {
     2 public:
     3     bool exist(vector<vector<char>>& board, string word) {
     4         int m=board.size();
     5         if(!m)
     6             return false;
     7         int n=board[0].size();
     8         if(word.length()==0)
     9             return false;
    10         
    11         vector<bool> temp(n,false);
    12         vector<vector<bool>> mark;
    13         for(int i=0;i<m;i++)
    14             mark.push_back(temp);
    15         
    16         for(int i=0;i<m;i++)
    17         {
    18             for(int j=0;j<n;j++)
    19             {
    20                 if(board[i][j]==word[0])
    21                 {
    22                     mark[i][j]=true;
    23                     if(deep(board,mark,1,word,i,j))
    24                         return true;
    25                     mark[i][j]=false;
    26                 }
    27             }
    28         }
    29         return false;
    30     }
    31     bool deep(vector<vector<char>>& board,vector<vector<bool>> mark,int p,string word,int x,int y)
    32     {
    33         if(p>=word.length())
    34             return true;
    35         int dir[4][2]={
    36             {0,-1},
    37             {0,1},
    38             {-1,0},
    39             {1,0}
    40         };
    41         for(int i=0;i<4;i++)
    42         {
    43             int tx=x+dir[i][0];
    44             int ty=y+dir[i][1];
    45             if(tx<0||tx>=board.size()||ty<0||ty>=board[0].size()||mark[tx][ty]==true)
    46                 continue;
    47             if(board[tx][ty]!=word[p])
    48                 continue;
    49             mark[tx][ty]=true;
    50             if(deep(board,mark,p+1,word,tx,ty))
    51                 return true;
    52             mark[tx][ty]=false;
    53         }
    54         return false;
    55     }
    56 };
    View Code
  • 相关阅读:
    异常
    抽象类
    java基础—接口3
    java基础—接口2
    java基础—接口1
    Android拍照适配方案
    继承—Car
    继承—矩形
    使用CSS和jQuery实现tab页
    纯CSS实现圆形进度条
  • 原文地址:https://www.cnblogs.com/jsir2016bky/p/5105962.html
Copyright © 2011-2022 走看看