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 exist(vector<vector<char> > &board, string word) {
int row = board.size();
int col = board[0].size();
vector<vector<bool> > visited(row, vector<bool>(col,false));
for (int r=0; r<row; r++)
{
for (int c=0; c<col; c++)
{
if (helper(board,word,r,c, row, col,0, visited))
return true;
}
}
return false;
}
bool helper(vector<vector<char>> &b, string word, int r, int c, int row, int col, int i, vector<vector<bool>> &visited)
{
if (i==word.length())
return true;
if (r>=row || r<0 || c<0 || c>=col)
return false;
if (visited[r][c])
return false;
if (b[r][c]!=word[i])
return false;
visited[r][c] = true;
//find neighbors if there are valid ones
bool ret= helper(b,word,r+1,c,row,col, i+1, visited)||helper(b,word,r-1,c,row,col,i+1,visited)
|| helper(b,word,r, c+1, row, col, i+1,visited) ||helper(b,word,r,c-1,row,col,i+1,visited);
visited[r][c]=false;
return ret;
}
};
No comments:
Post a Comment