一、JZ12 矩阵中的路径(中等)
1、回溯递归
import java.util.*;
public boolean hasPath(char[][] matrix, String word) {
char[] words = word.toCharArray();
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
//从[i,j]这个坐标开始查找
if (dfs(matrix, words, i, j, 0))
return true;
}
}
return false;
}
boolean dfs(char[][] matrix, char[] word, int i, int j, int index) {
//边界的判断,如果越界直接返回false。index表示的是查找到字符串word的第几个字符,
//如果这个字符不等于matrix[i][j],说明验证这个坐标路径是走不通的,直接返回false
if (i >= matrix.length || i < 0 || j >= matrix[0].length || j < 0 || matrix[i][j] != word[index])
return false;
//如果word的每个字符都查找完了,直接返回true
if (index == word.length - 1)
return true;
//把当前坐标的值保存下来,为了在最后复原
char tmp = matrix[i][j];
//然后修改当前坐标的值
matrix[i][j] = '.';
//走递归,沿着当前坐标的上下左右4个方向查找
boolean res = dfs(matrix, word, i + 1, j, index + 1)
|| dfs(matrix, word, i - 1, j, index + 1)
|| dfs(matrix, word, i, j + 1, index + 1)
|| dfs(matrix, word, i, j - 1, index + 1);
//递归之后再把当前的坐标复原
matrix[i][j] = tmp;
return res;
}
二、JZ13 机器人的运动范围(较难)
1、回溯递归
public class Solution {
public int movingCount(int threshold, int rows, int cols) {
boolean[][] array = new boolean[rows][cols];
int count = dfs(threshold, rows, cols, 0, 0, array);
return count;
}
private int dfs(int threshold, int rows, int cols, int row, int col, boolean[][] array) {
if(row < 0 || row >= rows || col < 0 || col >= cols || array[row][col] || sum(row) + sum(col) > threshold) {
return 0;
}
array[row][col] = true;
return 1 + dfs(threshold, rows, cols, row -1, col, array)
+dfs(threshold, rows, cols, row +1, col, array)
+dfs(threshold, rows, cols, row, col -1, array)
+dfs(threshold, rows, cols, row, col +1, array);
}
private int sum(int number) {
int sum = 1;
if(number >= 0 && number < 100) {
sum = number%10 + number/10;
}
return sum;
}
}