时间: 2020-11-22|48次围观|0 条评论

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 =

[
  ["ABCE"],
  ["SFCS"],
  ["ADEE"]
]

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

class Solution {
public:
bool check(vector<vector<char> > &board, string word, vector<vector<int>> &beUsed, int i, int j, int index)
{
    if (index==word.size())return true;
    int direction[4][2]={
   {-1,0},{
   1,0},{
   0,-1},{
   0,1}};
    for (int k=0;k<4;k++)
    {
        int ii=i+direction[k][0];
        int jj=j+direction[k][1];
        if(ii>=0&&ii<board.size()&&jj>=0&&jj<board[0].size()&&!beUsed[ii][jj]&&board[ii][jj]==word[index])
        {
            beUsed[ii][jj]=1;
            if(check(board,word,beUsed,ii,jj,index+1))return true;
            beUsed[ii][jj]=0;
        }
    }
    return false;
}
bool exist(vector<vector<char> > &board, string word) 
{
    if(word.size()==0)return true;
    vector<vector<int>> beUsed(board.size(),vector<int> (board[0].size(),0));
    for (int i=0;i<board.size();i++)
    {
        for (int j=0;j<board[i].size();j++)
        {
            if (board[i][j]==word[0])
            {
                beUsed[i][j]=1;
                if (check(board, word, beUsed, i, j, 1))return true;
                beUsed[i][j]=0;
            }
        }
    }
    return false;
}
};

 

转载于:https://www.cnblogs.com/Vae1990Silence/p/4281452.html

原文链接:https://blog.csdn.net/weixin_30342827/article/details/96788093

本站声明:网站内容来源于网络,如有侵权,请联系我们,我们将及时处理。

本博客所有文章如无特别注明均为原创。
复制或转载请以超链接形式注明转自起风了,原文地址《leetcode[79]Word Search
   

还没有人抢沙发呢~