leetcode[79]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 =

[
  ["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