题目:给定一个 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
提示:
- m == board.length
- n = board[i].length
- 1 <= m, n <= 6
- 1 <= word.length <= 15
- board 和 word 仅由大小写英文字母组成
进阶:你可以使用搜索剪枝的技术来优化解决方案,使其在 board 更大的情况下可以更快解决问题?
相关标签:数组
、回溯
、矩阵
解析:这题大体思路就是先找到单词的起点位置,然后根据上下左右四个方向找符合条件的字符,同时考虑到不能重复使用同一个位置的字符这个条件,可以把访问过的路径的字符置为*号,遍历过后替换回来。具体代码如下所示:
public boolean exist(char[][] board, String word) {
char[] arr = word.toCharArray();
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
if(dfs(board,arr,i,j,0)){
return true;
}
}
}
return false;
}
public boolean dfs(char[][] board,char[] arr,int i,int j,int index){
//判断边界条件(中断条件)
if(i<0 || i>=board.length || j<0 || j>=board[0].length || board[i][j]!=arr[index]){
return false;
}
//如果遍历完成(结束条件)
if(index == arr.length-1){
return true;
}
//保存当前表格里的字符
char temp = board[i][j];
//将走过的路径设置成*,防止重复
board[i][j] = '*';
//继续判断上下左右四个方向
boolean top = dfs(board,arr,i-1,j,index+1);
boolean bottom = dfs(board,arr,i+1,j,index+1);
boolean right = dfs(board,arr,i,j+1,index+1);
boolean left = dfs(board,arr,i,j-1,index+1);
//将之前替换的字符还原
board[i][j] = temp;
return top || bottom || right || left;
}
每天进步一点点~