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);     
    }
};
相关推荐
小指纹1 小时前
图论-最短路Dijkstra算法
数据结构·c++·算法·深度优先·图论
王德博客2 小时前
【从基础到实战】STL string 学习笔记(上)
c++·笔记·学习
赴3352 小时前
逻辑回归 银行贷款资格判断案列优化 交叉验证,调整阈值,下采样与过采样方法
算法·机器学习·逻辑回归·下采样·交叉验证·过采样·阈值
2501_924878732 小时前
无人机光伏巡检缺陷检出率↑32%:陌讯多模态融合算法实战解析
开发语言·人工智能·算法·视觉检测·无人机
沉睡的无敌雄狮3 小时前
无人机光伏巡检漏检率↓78%!陌讯多模态融合算法实战解析
人工智能·算法·计算机视觉·目标跟踪
Algebraaaaa3 小时前
C++ 中 NULL 与 nullptr 有什么区别?
开发语言·c++
magicwt3 小时前
《从零构建大模型》读书笔记
算法
大胖猫L3 小时前
深搜与广搜在 TypeScript 类型递归中的应用
前端·算法
2202_756749694 小时前
02 基于sklearn的机械学习-KNN算法、模型选择与调优(交叉验证、朴素贝叶斯算法、拉普拉斯平滑)、决策树(信息增益、基尼指数)、随机森林
python·算法·决策树·随机森林·机器学习·sklearn
ATaylorSu4 小时前
经典算法之美:冒泡排序的优雅实现
开发语言·笔记·学习·算法