剑指offer-65.机器人的运动范围

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zxm1306192988/article/details/82055287

牛客

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

题解:

深度搜索四个方向,注意递归退出的条件。
用一个全局变量,记录满足条件的结点个数。

class Solution {

    private final static int[][] next = { { 0, -1 }, { 0, 1 }, { -1, 0 }, { 1, 0 } };
    private int cnt = 0;
    private int rows;
    private int cols;
    private int threshold;

    public int movingCount(int threshold, int rows, int cols) {
        this.rows = rows;
        this.cols = cols;
        this.threshold = threshold;
        boolean[][] marked = new boolean[rows][cols];
        dfs(marked, 0, 0);
        return cnt;
    }

    private void dfs(boolean[][] marked, int r, int c) {
        if (r < 0 || r >= rows || c < 0 || c >= cols || marked[r][c]) {// 如果超过范围,或已经访问过,则返回
            return;
        }
        marked[r][c] = true; // 访问这个结点
        if (getNumberSum(r, c) > threshold) { // 不满足条件返回
            return;
        }
        cnt++; // 成功访问,计数器加一
        for (int[] n : next) { // 深度搜索四个方向
            dfs(marked, r + n[0], c + n[1]);
        }
    }

    private int getNumberSum(int i, int j) { // 返回每位数字之和
        int cnt = 0;
        while (i / 10 != 0) {
            cnt += i % 10;
            i = i / 10;
        }
        cnt += i % 10;
        while (j / 10 != 0) {
            cnt += j % 10;
            j = j / 10;
        }
        cnt += j % 10;
        return cnt;
    }
}

猜你喜欢

转载自blog.csdn.net/zxm1306192988/article/details/82055287