题目:
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.
Constraints:
board
andword
consists only of lowercase and uppercase English letters.1 <= board.length <= 200
1 <= board[i].length <= 200
1 <= word.length <= 10^3
首先遍历找到第一个元素,然后进行深度优先遍历。需要注意的是dfs有返回值,那么每次递归调用都要处理返回值,要return
其次,由于匹配的前一个字母也在相邻的位置,而又不能再匹配,因此,要对已经匹配的位置进行标记。如果后面的匹配失败,前面已经标记的也要回溯的时候重新置位false,这个点还真有点绕。字符串“ABCB”就是这种情况。
class Solution {
public:
int dx[4] = {0,0,1,-1};
int dy[4] = {1,-1,0,0};
int Row,Col;
bool visited[200][200];
bool dfsBoard(vector<vector<char> > &board,int i,int j,string word,int cnt)
{
if(cnt >= word.length())
{
if(cnt == word.length())
return true;
else
return false;
}
for(int k = 0; k < 4; k++)
{
int nx = i + dx[k];
int ny = j + dy[k];
if(nx >= 0 && nx < Row && ny >= 0 && ny < Col)
{
if(board[nx][ny] == word[cnt] && !visited[nx][ny])
{
visited[nx][ny] = true;
if(dfsBoard(board,nx,ny,word,cnt + 1))
return true;
visited[nx][ny] = false;
}
}
}
return false;
}
bool exist(vector<vector<char>>& board, string word) {
int len = word.length();
if(len == 0) return true;
int m = board.size();
if(m == 0) return false;
int n = board[0].size();
if(n == 0) return false;
Row = m, Col = n;
memset(visited,false,200*200);
for(int i = 0; i < m; i++)
{
for(int j = 0; j < n; j++)
{
if(board[i][j] == word[0] && !visited[i][j])
{
visited[i][j] = true;
if(true == dfsBoard(board,i,j,word,1))
return true;
visited[i][j] = false;
}
}
}
return false;
}
};