剑指Offer Java版 面试题13:机器人的运动范围

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

练习地址

https://www.nowcoder.com/practice/6e5207314b5241fb83f2329e89fdecc8
https://leetcode-cn.com/problems/ji-qi-ren-de-yun-dong-fan-wei-lcof/

参考答案(回溯法)

public class Solution {
    public int movingCount(int threshold, int rows, int cols) {
        if (threshold < 1 || rows < 1 || cols < 1) {
            return 0;
        }
        boolean[][] visited = new boolean[rows][cols];
        return movingCount(threshold, rows, cols, 0, 0, visited);
    }
    
    private int movingCount(int threshold, int rows, int cols, int row, int col, boolean[][] visited) {
        int count = 0;
        if (row >= 0 && row < rows && col >= 0 && col < cols && !visited[row][col]
            && sum(row) + sum(col) <= threshold) {
            visited[row][col] = true;
            count = 1 + movingCount(threshold, rows, cols, row - 1, col, visited)
                + movingCount(threshold, rows, cols, row + 1, col, visited)
                + movingCount(threshold, rows, cols, row, col + 1, visited)
                + movingCount(threshold, rows, cols, row, col - 1, visited);
        }
        return count;
    }
    
    private int sum(int number) {
        int sum = 0;
        while (number > 0) {
            sum += number % 10;
            number /= 10;
        }
        return sum;
    }
}

复杂度分析

  • 时间复杂度:O(mn)。
  • 空间复杂度:O(mn)。

其中,m和n分别代表行数和列数。

👉剑指Offer Java版目录
👉剑指Offer Java版专题

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容