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.
Example:
board =
[
[‘A’,‘B’,‘C’,‘E’],
[‘S’,‘F’,‘C’,‘S’],
[‘A’,‘D’,‘E’,‘E’]
]
Given word = “ABCCED”, return true.
Given word = “SEE”, return true.
Given word = “ABCB”, return false.
C++
bool exist(vector<vector<char>>& board, string word) {
int height = board.size();
int width = board[0].size();
vector<vector<bool>> visit(height,vector<bool>(width,false));
for(int i = 0;i < height;++i)
{
for(int j = 0;j < width;++j)
{
if(DFS(board,visit,word,i,j,0))
return true;
}
}
return false;
}
bool DFS(vector<vector<char>>& board,vector<vector<bool>>& visit,string& word,int i,int j,int count)
{
int U = board[0].size();
int V = board.size();
if(i < 0||j < 0||i >= V||j >= U||word[count] != board[i][j]||visit[i][j])
return false;
if(count == word.size() - 1&&word[count] == board[i][j])
return true;
visit[i][j] = true;
bool res = DFS(board,visit,word,i - 1,j,count + 1)||
DFS(board,visit,word,i,j + 1,count + 1)||
DFS(board,visit,word,i + 1,j,count + 1)||
DFS(board,visit,word,i,j - 1,count + 1);
visit[i][j] = false;
return res;
}