单词搜索
题目描述:
给定一个二维网格和一个单词,找出该单词是否存在于网格中。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
示例:
board =
[
[‘A’,‘B’,‘C’,‘E’],
[‘S’,‘F’,‘C’,‘S’],
[‘A’,‘D’,‘E’,‘E’]
]
给定 word = “ABCCED”, 返回 true
给定 word = “SEE”, 返回 true
给定 word = “ABCB”, 返回 false
思路:从每个点开始深搜,用一个状态矩阵判断当前位置是否走过。
代码:
class Solution {
public boolean exist(char[][] board, String word) {
int f[][] = new int[board.length][board[0].length];//判断是否走过
for(int i = 0 ; i<board.length;i++){
for(int j=0 ; j<board[i].length; j++){
if(dfs(i,j,board,word,0,f)) return true;
}
}
return false;
}
public boolean dfs(int i,int j,char[][] board, String word,int op,int [][]f){
if(op == word.length()) return true; //返回真 因为word字符串全部走过了
//越界
if(i<0||j<0) return false;
if(i>=board.length||j>=board[0].length) return false;
if(board[i][j] != word.charAt(op)) return false ;
if(f[i][j] !=0) return false;//该点走过了
else{
f[i][j] = 1;
if(dfs(i-1,j,board,word,op+1,f)||dfs(i+1,j,board,word,op+1,f)||dfs(i,j-1,board,word,op+1,f)||dfs(i,j+1,board,word,op+1,f))
return true;//如果成功就直接返回真
f[i][j]=0;//重新置0
}
return false;
}
}
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/word-search