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
.
class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
if(board.size()&&board[0].size()&&word.length())
for(int i=0;i<board.size();i++)
for(int j=0;j<board[0].size();j++)
if(isfound(board,word,i,j,0))
return true;
return false;
}
bool isfound(vector<vector<char>>& board,const string& word,int row,int col,int pos){
char temp = board[row][col];
bool res = false;
char c=board[row][col];
if(c!=word[pos])
return false;
if(pos==word.size()-1)
return true;
board[row][col]='*';
if(!res&&row>0)
res=isfound(board,word,row-1,col,pos+1);
if(!res&&col>0)
res=isfound(board,word,row,col-1,pos+1);
if(!res&&row<board.size()-1)
res=isfound(board,word,row+1,col,pos+1);
if(!res&&col<board[0].size()-1)
res=isfound(board,word,row,col+1,pos+1);
board[row][col]=temp;
return res;
}
};