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 =
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) {
vector<bool> line = vector<bool>(board[0].size(),false);
vector<vector<bool>> visited = vector<vector<bool>>(board.size(),line);
if (word.size()<=0)
return true;
for (int i=0;i<board.size();i++)
{
for (int j=0;j<board[0].size();++j)
{
if (board[i][j]==word[0])
{
if (dfs(board,visited,word,1,i,j))
return true;
}
}
}
return false;
}
bool dfs(vector<vector<char>> &board, vector<vector<bool>>& visited, string word, int pos, int i,int j)
{
if (pos>=word.size())
return true;
visited[i][j] = true;
if (i>=1 && board[i-1][j]==word[pos] && !visited[i-1][j] && dfs(board,visited,word,pos+1,i-1,j))
return true;
if (i+1<board.size() && board[i+1][j]==word[pos] && !visited[i+1][j] && dfs(board,visited,word,pos+1,i+1,j))
return true;
if (j>=1 && board[i][j-1]==word[pos] && !visited[i][j-1] && dfs(board,visited,word,pos+1,i,j-1))
return true;
if (j+1<board[0].size() && board[i][j+1]==word[pos] && !visited[i][j+1] && dfs(board,visited,word,pos+1,i,j+1))
return true;
visited[i][j]=false;
return false;
}
};
No comments:
Post a Comment