剑指offer10

题目描述

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

解题思路分析

这道题也是一个典型的回溯问题,但是这道题题意指定了只能从(0,0)开始进行移动,所以相对于剑指offer09,这道题就相对来说简单一点了,同样的我们应该分析回溯结束条件和边界问题
从这道题来看,这道题的结束条件同样是需要将所有可以找到的路径都找到,所以这道题需要所有的遍历
同样的,边界问题其中矩阵的边界问题,而且需要满足进入的方格的各个数字之和不能大于给定的threshold值

代码实现

public int movingCount(int threshold, int rows, int cols) {
    boolean[][] vis = new boolean[rows][cols];
    return search(threshold, rows, cols, 0, 0, vis);
}

private int search(int threshold, int rows, int cols, int r, int c, boolean[][] vis) {
    // 每次递归的结束条件
    if (r < 0 || r >= rows || c < 0 || c >= cols || sumNum(r) + sumNum(c) > threshold || vis[r][c]) {
        return 0;
    }
    // 标记该点是否访问过
    vis[r][c] = true;
    //计算访问的节点数
    return search(threshold, rows, cols, r - 1, c, vis) +
           search(threshold, rows, cols, r + 1, c, vis) +
           search(threshold, rows, cols, r, c - 1, vis) +
           search(threshold, rows, cols, r, c + 1, vis) + 1;
}

//计算数的每个位置的数字之和
private int sumNum(int n) {
    int sum = 0;
    while (n > 0) {
        sum += n % 10;
        n /= 10;
    }
    return sum;
}

你可能感兴趣的:(剑指offer10)