JZ13 机器人的运动范围

机器人的运动范围_牛客题霸_牛客网

地上有一个 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 0≤threshold≤15 ,1≤rows,cols≤100 1≤rows,cols≤100

m = 10, n = 5

00 01 02 03 04 05 06 07 08 09

10 11 12 13 14 15 16 17 18 19

20 21 22 23 24 25 26 27 28 29

30 31 32 33 34 35 36 37 38 39

40 41 42 43 44 45 46 47 48 49

if thresold = 3, 能走的路径:00 01 02 03,10,11 ,12,20 ,21,30, row+col <=3

if thresold = 8,能走的路径: 00~08, 10~17, 20~26,30~35,40~44, row+col<=8

数位和:123456----->1+2+3+4+5+6,

row = 10, col = 11 ------>数位和:1+0+1+1 = 3

cpp 复制代码
#include <vector>
class Solution {
public:
    int movingCount(int threshold, int rows, int cols) {
        if(threshold < 0 || rows <= 0 || cols <= 0){
            return 0;
        }

        vector<vector<bool>> visited(rows, vector<bool> (cols, false));

        int count = movingCountCore(threshold, rows, cols, 0, 0, visited);
        return count;
    }
    //数位之和
    int getDigitSum(int number){ //row = 10, column = 11, 数位之和sum = 3
        int sum = 0;
        while(number>0){
            sum += number%10;
            number /= 10;
        }
        return sum;
    }
    int movingCountCore(int threshold,int rows, int cols, int row, int column, vector<vector<bool>> &visited){
        
        if(row < 0 ||row >= rows ||
         column <0 || column >= cols||
         getDigitSum(row) + getDigitSum(column) > threshold //数位之和
        //  row + column > threshold //row < 10, column < 10这种情况是可以的, 
                                    //row=10,column = 10的时候,数位之和 sum = 2
         || visited[row][column]   //true表示已访问
         ) return false;

         visited[row][column] = true;
                //往四个方向dfs
        return 1+movingCountCore(threshold, rows, cols, row+1, column, visited)+ 
                movingCountCore(threshold, rows, cols, row-1, column, visited)+
                movingCountCore(threshold, rows, cols, row, column+1, visited)+
                movingCountCore(threshold, rows-1, cols, row, column-1, visited);     
    }
};
相关推荐
dialect_1 小时前
KMP算法
开发语言·c++·算法
weixin_468466851 小时前
从“看懂”到“做到”:视觉-语言-动作模型如何让机器人真正执行指令
人工智能·ai·机器人·大语言模型·前沿科技
reikocao1 小时前
卡尔曼滤波的动态机制:P如何改变融合权重
算法
漂流瓶jz2 小时前
UVA-1612 猜名次 题解答案代码 算法竞赛入门经典第二版
数据结构·算法·题解·排序·aoapc·算法竞赛入门经典
吞下星星的少年·-·2 小时前
Div.2 CF 1130B题(构造,贪心)
算法·贪心·构造
ShineWinsu3 小时前
对于Qt:QRadioButton常见属性以及QButtonGroup的解析
数据库·c++·qt·microsoft·gui·qradiobutton·qbuttongroup
云智慧AIOps社区3 小时前
智能巡检机器人应用场景解析:机房巡检、园区安防、管廊巡视与展厅导览
人工智能·机器人·具身智能·智能巡检机器人·企业级智能巡检机器人·机房巡检机器人·导览机器人
傲世仙尊3 小时前
多态-虚表才活到运行期符号表早已消失
c++
GlobalInfo4 小时前
重磅发布 | 2026年船体清洁机器人行业研究报告:市场规模、发展前景与十五五战略地图
大数据·人工智能·机器人
chenbingjie_c4 小时前
C++ 多态完全指南:从虚函数重写到虚函数表原理
开发语言·c++