class Solution {
public:
bool exist(vector<vector<char> > &board, string word) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
for(int i=0;i<board.size();++i){
for(int j=0;j<board[0].size();++j){
if(board[i][j]==word[0]){
vector<vector<char> > tmp(board);
if(helper(tmp,i,j,word,0))
return true;
}
}
}
}
bool helper(vector<vector<char> >& board,int i,int j,string& word,int index){
if(index==word.size())
return true;
if(i>=0&&i<board.size()&&j>=0&&j<board[0].size()&&word[index]==board[i][j]){
board[i][j]='*';
++index;
return helper(board,i+1,j,word,index)||helper(board,i,j+1,word,index)||helper(board,i,j-1,word,index)||helper(board,i-1,j,word,index);
}
return false;
}
};
Leetcode: Word Search
最新推荐文章于 2021-10-20 23:02:10 发布