【剑指Offer】13.机器人的运动范围

题目

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

数据范围:0≤threshold≤15 ,1≤rows,cols≤100

进阶:空间复杂度 O(nm) ,时间复杂度 O(nm)

示例1

输入:1,2,3

返回值:3

示例2

输入:0,1,3

返回值:1

示例3

输入:10,1,100

返回值:29

说明:[0,0],[0,1],[0,2],[0,3],[0,4],[0,5],[0,6],[0,7],[0,8],[0,9],[0,10],[0,11],[0,12],[0,13],[0,14],[0,15],[0,16],[0,17],[0,18],[0,19],[0,20],[0,21],[0,22],[0,23],[0,24],[0,25],[0,26],[0,27],[0,28] 这29种,后面的[0,29],[0,30]以及[0,31]等等是无法到达的

示例4

输入:5,10,10

返回值:21

解答

源代码

java 复制代码
import java.util.*;

public class Solution {
    public int movingCount(int threshold, int rows, int cols) {
        boolean[][] flag = new boolean[rows][cols];
        return dfs(threshold, rows, cols, 0, 0, flag);
    }

    public int dfs(int threshold, int rows, int cols, int i, int j, boolean[][] flag) {
        if (i < 0 || i >= rows || j < 0 || j >= cols || flag[i][j] || cal(i) + cal(j) > threshold) {
            return 0;
        }

        flag[i][j] = true;
        return 1 + dfs(threshold, rows, cols, i - 1, j, flag)
                        + dfs(threshold, rows, cols, i + 1, j, flag)
                        + dfs(threshold, rows, cols, i, j - 1, flag)
                        + dfs(threshold, rows, cols, i, j + 1, flag);
    }

    public int cal(int number) {
        int sum = 0;
        while (number != 0) {
            sum += number % 10;
            number /= 10;
        }

        return sum;
    }
}

总结

迷宫问题,回溯就完事,记得做标记避免重复经过方格。

这里要注意求的是机器人的运动"范围"而不是一条最大路径,所以每次应该加上上下左右路径的所有长度,而不是只加上一条最长的路径。

相关推荐
tg-zm8899961 小时前
2025返利商城源码/挂机自动收益可二开多语言/自定义返利比例/三级分销理财商城
java·mysql·php·laravel·1024程序员节
X***C8621 小时前
SpringBoot:几种常用的接口日期格式化方法
java·spring boot·后端
Promise4851 小时前
贝尔曼公式的迭代求解笔记
笔记·算法
前端达人1 小时前
你的App消息推送为什么石沉大海?看Service Worker源码我终于懂了
java·开发语言
小光学长1 小时前
基于ssm的宠物交易系统的设计与实现850mb48h(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
java·前端·数据库
编程大师哥1 小时前
vxe-table 透视表分组汇总及排序基础配置
java
8***84822 小时前
spring security 超详细使用教程(接入springboot、前后端分离)
java·spring boot·spring
9***J6282 小时前
Spring Boot项目集成Redisson 原始依赖与 Spring Boot Starter 的流程
java·spring boot·后端
M***Z2102 小时前
SQL 建表语句详解
java·数据库·sql
v***7942 小时前
Spring Boot 热部署
java·spring boot·后端