《剑指Offer》13. 机器人的运动范围

题目链接

牛客网

题目描述

地上有一个 m 行和 n 列的方格。一个机器人从坐标 (0, 0) 的格子开始移动,每一次只能向左右上下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于 k 的格子。

例如,当 k 为 18 时,机器人能够进入方格 (35,37),因为 3+5+3+7=18。但是,它不能进入方格 (35,38),因为 3+5+3+8=19。请问该机器人能够达到多少个格子?

解题思路

dfs思想,不需要回溯,访问只用来计数

public class Solution {
    private int threshold, m, n, cnt;
    private int[][] directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
    private int[][] sumXY;
    public int movingCount(int threshold, int rows, int cols) {
        this.threshold = threshold; m = rows; n = cols; 
        cnt = 0;
        boolean[][] marked = new boolean[m][n];
        initSumXY();
        dfs(marked, 0, 0);
        return cnt;
    }
    private void initSumXY() {
        int[] sumNum = new int[Math.max(m, n)];
        for (int i=0;i<sumNum.length;i++) {
            int n = i;
            while (n!=0) {
                sumNum[i] += n%10;
                n = n/10;
            }
        }
        sumXY = new int[m][n];
        for (int i=0;i<m;i++) 
            for (int j=0;j<n;j++) 
                sumXY[i][j] = sumNum[i]+sumNum[j];
    }
    private void dfs(boolean[][] marked, int i, int j) {
        if (i<0 || i>=m || j<0 || j>=n || marked[i][j]) return;
        marked[i][j] = true;
        if (sumXY[i][j] > threshold) return;
        cnt++;
        for (int[] d: directions)
            dfs(marked, i+d[0], j+d[1]);
    }
}
发布了206 篇原创文章 · 获赞 32 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/weixin_38611497/article/details/104134130