剑指offer(十八)

题目:64.矩阵中的路径,65.机器人的运动范围

64. 矩阵中的路径

请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。 例如 a b c e s f c s a d e e 矩阵中包含一条字符串”bcced”的路径,但是矩阵中不包含”abcb”路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。

思路:这是一个搜索问题,可以用回溯法解决。给定任意一个格子作为起点,若格子字符等于str起始字符,则可以往四个方向走,递归判断下个格子是否与str的下个字符相等。用一个flag数组保存格子是否被走过,若走过则标记为true,下次若需要再经过该格子,则返回false。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class Solution {
    public boolean hasPath(char[] matrix, int rows, int cols, char[] str){
        boolean[] flag = new boolean[matrix.length];
        for(int i = 0; i < rows; i++){
            for(int j = 0; j < cols; j++){
                if(hasPath(matrix, rows, i, cols, j, str, 0, flag)) return true;
            }
        }
        return false;
    }
    public boolean hasPath(char[] matrix, int rows, int i, int cols, int j, char[] str, int k, boolean[] flag){
        int index = i * cols + j;
        if(i < 0 || i > rows - 1 || j < 0 || j > cols - 1|| k > str.length - 1 || matrix[index] != str[k] || flag[index]) return false;
        if(k == str.length - 1) return true;
        flag[index] = true;
        if(hasPath(matrix, rows, i + 1, cols, j, str, k + 1, flag) ||
          hasPath(matrix, rows, i, cols, j + 1, str, k + 1, flag) ||
          hasPath(matrix, rows, i - 1, cols, j, str, k + 1, flag) ||
          hasPath(matrix, rows, i, cols, j - 1, str, k + 1, flag)){
            return true;
        }
        flag[index] = false;
        return false;
    }
}

65. 机器人的运动范围

地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?

思路: 逐个判断机器人走的格子是否是合法的,走过的格子用一个flag二维数组记录减少循环。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class Solution {
    private static int count = 0;
    public int movingCount(int threshold, int rows, int cols){
        boolean [][] flag = new boolean[rows][cols];
        return helper(threshold, rows, 0, cols, 0, flag);
    }
    

    public int helper(int threshold ,int rows, int i, int cols, int j, boolean[][] flag){
        if(i < 0 || j < 0 || i >= rows || j >= cols || flag[i][j] || sumN(i) + sumN(j) > threshold) return 0;
    
        flag[i][j] = true;
        return helper(threshold, rows, i - 1, cols, j, flag) 
            + helper(threshold, rows, i + 1, cols, j, flag) 
            + helper(threshold, rows, i, cols, j - 1, flag) 
            + helper(threshold, rows, i, cols, j + 1, flag) + 1;
    }
    
    public int sumN(int loc){
        int sum = 0;
        while(loc != 0){
            sum += loc % 10;
            loc /= 10;
        }
        return sum;
    }
}