给定一个 m x n 二维字符网格 board 和一个字符串单词 word 。如果 word 存在于网格中,返回 true ;否则,返回 false 。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
示例 1:
输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
输出:true
示例 2:
输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE"
输出:true
示例 3:
输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB"
输出:false
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/word-search
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
//一共四个方向
int [] dx = new int[]{0,0,1,-1};
int [] dy = new int[]{1,-1,0,0};
public boolean exist(char[][] board, String word) {
for(int i =0;i<board.length;i++){
for(int j=0;j<board[i].length;j++){
if (dfs(board,word,0,i,j)){
return true;
}
}
}
return false;
}
public boolean dfs(char[][] board,String word,int index,int x ,int y){
if(board[x][y]!=word.charAt(index)){
return false;
}
if(index == word.length()-1){
return true;
}
char temp = board[x][y];
//设置为访问状态
board[x][y] = '.';
for(int i =0;i<4;i++){
int new_x = x+dx[i];
int new_y = y+dy[i];
//处理边界条件
if(new_x<0 ||new_x> board.length-1 ||new_y<0||new_y>board[0].length-1||board[new_x][new_y] == '.'){
continue;
}
if(dfs(board,word,index+1,new_x,new_y)) return true;
}
//访问完成之后进行还原
board[x][y] = temp;
return false;
}
}