给定一个二维网格和一个单词,找出该单词是否存在于网格中。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
示例:
board =
[
[‘A’,‘B’,‘C’,‘E’],
[‘S’,‘F’,‘C’,‘S’],
[‘A’,‘D’,‘E’,‘E’]
]
给定 word = “ABCCED”, 返回 true.
给定 word = “SEE”, 返回 true.
给定 word = “ABCB”, 返回 false.
解题思路:
这个题我们设计递归的想法,对上下左右四个方向每次递归,用visited记录走过的路径,
class Solution {
public:
bool dfs(vector<vector<char>>&board,int i,int j,string word, vector<vector<int>>&visited,int x){
if(i<0||i>=board.size()||j<0||j>=board[0].size()||board[i][j]!=word[x]||x>=word.size()||visited[i][j]){
return 0;
}else if(x==word.size()-1 && board[i][j]==word[x]){
return 1;
}else{
visited[i][j]=1;
bool row1 = dfs(board,i+1,j,word,visited,x+1);
if(row1){
return 1;
}
bool row2 = dfs(board,i-1,j,word,visited,x+1);
if(row2){
return 1;
}
bool col1 = dfs(board,i,j+1,word,visited,x+1);
if(col1){
return 1;
}
bool col2 = dfs(board,i,j-1,word,visited,x+1);
if(col2){
return 1;
}
//当遍历完所有方向没找到对应的字符,则visited[i][j]=0;
//return 0;
visited[i][j]=0;
return 0;
}
}
bool exist(vector<vector<char>>& board, string word) {
int row = board.size();
int col = board[0].size();
//visited的作用是记录已经走过的路径,初始化为0,当走过则
//计为1,当再次遍历到这个点的时候,直接return 0;
vector<vector<int>>visited(row,vector<int>(col,0));
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
if(word[0]==board[i][j]&&dfs(board,i,j,word,visited,0)){
return 1;
}
}
}
return 0;
}
};
同样的思想,Python3实现:
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
row = len(board)
col = len(board[0])
def helper(i,j,visited,x1): # 这里注意符号的选择,别重复
if x1 == len(word):
return True
for x,y in [(-1,0),(1,0),(0,1),(0,-1)]:
temp_i = x+i
temp_j = y+j
if 0<=temp_i<row and 0<=temp_j<col and board[temp_i][temp_j] == word[x1] \
and (temp_i,temp_j) not in visited:
visited.add((temp_i,temp_j))
if helper(temp_i,temp_j,visited,x1+1):
return True
visited.remove((temp_i,temp_j)) #回溯
return False
for i in range(row):
for j in range(col):
if board[i][j] == word[0] and helper(i, j,{(i, j)},1):
return True
return False