leetcode链接:https://leetcode-cn.com/problems/ju-zhen-zhong-de-lu-jing-lcof/
题目
解法
使用 dfs(深度遍历搜索)
class Solution {
public boolean exist(char[][] board, String word) {
// 行数
int row = board.length;
// 列数
int col = board[0].length;
char[] chars = word.toCharArray();
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (dfs(board, chars, i, j, 0)) {
return true;
}
}
}
return false;
}
boolean dfs(char[][] board, char[] word, int i, int j, int index) {
// 参数说明,index指查到字符串的第几个字符
// 边界判断
// 1.如果越界直接返回false
// 2.如果当前字符不等于board[i][j],说明此路不通,返回false
if (i >= board.length || i < 0 || j >= board[0].length || j < 0 || board[i][j] != word[index]) {
return false;
}
// 如果index=word.length,说明匹配成功,返回true
if (index == word.length-1 ) {
return true;
}
// 保存中间值,方便复原
char tmp = board[i][j];
// 将当前位置标记为已访问
board[i][j] = '.';
boolean res = dfs(board, word, i - 1, j, index + 1) ||
dfs(board, word, i + 1, j, index + 1) ||
dfs(board, word, i, j - 1, index + 1) ||
dfs(board, word, i, j + 1, index + 1);
// 复原环境
board[i][j] = tmp;
return res;
}
}