剑指offer 机器人的运动范围

题目:

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

代码:

复制代码
 1 class Solution {
 2 public:
 3     int movingCount(int threshold, int rows, int cols)
 4     {
 5         bool* finish = new bool[rows*cols]();
 6         return Count(threshold, rows, cols, finish, 0, 0 );
 7     }
 8     int Count(int threshold, int rows, int cols, bool* fin, int x, int y ){
 9         if(x < 0 || x >=rows || y < 0 || y >= cols || fin[x*cols+y] ||BitSum(x)+BitSum(y) > threshold )
10             return false;
11         fin[x*cols+y] = true;
12         return Count(threshold, rows, cols, fin, x - 1, y )
13             + Count(threshold, rows, cols, fin, x + 1, y )
14             + Count(threshold, rows, cols, fin, x, y - 1 )
15             + Count(threshold, rows, cols, fin, x, y + 1 )
16             + 1;
17     }
18     int BitSum(int t) {
19         int count = 0;
20         while(t){
21             count += t %10;
22             t /= 10;
23         }
24         return count;
25     }
26 };
复制代码

我的笔记: 

  从(0,0)开始走,每成功走一步标记当前位置为true,然后从当前位置往四个方向探索,
返回1 + 4 个方向的探索值之和。
  探索时,判断当前节点是否可达的标准为:
  • 1)当前节点在矩阵内;
  • 2)当前节点未被访问过;
  • 3)当前节点数值满足限制。
posted @   John_yan15  阅读(111)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示