剑指 Offer 12. 矩阵中的路径
题目:
思路:
主要是对矩阵进行搜索类,可以使用回溯法,主要思想就是由某一个点,向其他方向进行递归。
代码:
class Solution {
public boolean exist(char[][] board, String word) {
boolean[][] valite = new boolean[board.length][board[0].length];
char[] chars = word.toCharArray();
int w = 0;
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
if (backTrack(board, chars, valite, i, j, w)) {
return true;
}
}
}
return false;
}
public boolean backTrack(char[][] board, char[] chars, boolean[][] valite, int i, int j, int w) {
// false条件
if (i < 0 || i > board.length - 1 || j < 0 || j > board[i].length - 1 || w > chars.length - 1 || valite[i][j] || board[i][j] != chars[w]) {
return false;
}
// true条件
if (w == chars.length-1 && board[i][j] == chars[w]) {
return true;
}
// 不能重复进入
valite[i][j] = true;
// 向四个方向进行遍历
result = backTrack(board, chars, valite, i - 1, j, w + 1) ||
backTrack(board, chars, valite, i + 1, j, w + 1) ||
backTrack(board, chars, valite, i, j - 1, w + 1) ||
backTrack(board, chars, valite, i, j + 1, w + 1);
// 每次新进入一个i,j,都要进行重置
valite[i][j] = false;
return result;
}
}