方法:深度优先搜索DFS | 回溯
每次DFS都需要遍历4个方向
设置二维数组visited,用来保存每次DFS遍历过的点
DFS:
剪枝
终止条件
令此时所对应的visited为1
四个方向遍历:
满足边界条件且没有访问过:
如果DFS后为真,也即找到一个匹配:
就返回True
还原现场
都没找到就返回False
DFS是从一个点的深度优先搜索,在 exist的函数里循环遍历所有的坐标,如果该点的字符为word的第一个字符,且DFS结果为真(表示找到
一个匹配),就返回真。遍历完都没找到,就返回假。
Python实现:
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
directions = [(1,0),(0,-1),(-1,0),(0,1)]
if (not board or not board[0]) and word:
return False
def dfs(k,x,y):
if board[x][y] != word[k]:
return False
if k == len(word) -1:
return True
visited[x][y] = 1
for i,j in directions:
x1 = x + i
y1 = y + j
if 0 <= x1 < len(board) and 0 <= y1 < len(board[0]) and visited[x1][y1] == 0:
if dfs(k + 1,x1,y1):
return True
visited[x][y] = 0
return False
m,n = len(board),len(board[0])
visited = [[0] * n for _ in range(m)]
for i in range(m):
for j in range(n):
if word[0] == board[i][j] and dfs(0,i,j):
return True
return False
C++实现:
class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
// DFS
int m = board.size(),n = board[0].size();
vector<vector<int>> visited(m,vector<int>(n));
for (int i = 0;i < m ;i++){
for (int j = 0;j < n;j++){
if (board[i][j] == word[0] && dfs(board,visited,word,i,j,0)){
return true;
}
}
}
return false;
}
bool dfs(vector<vector<char>>& board,vector<vector<int>>& visited,string& word,int i,int j ,int k){
if (board[i][j] != word[k]){
return false;
}
if (k == word.size() - 1 ){
return true;
}
visited[i][j] = 1;
vector<pair<int,int>> directions{
{
1,0},{
0,-1},{
-1,0},{
0,1}};
for (const auto& dir:directions){
int x = i + dir.first,y = j + dir.second;
if (x >= 0 && x < board.size() && y >= 0 && y < board[0].size() && !visited[x][y]){
if (dfs(board,visited,word,x,y,k+1)){
return true;
}
}
}
visited[i][j] = 0;
return false;
}
};