当前位置:网站首页>机器人的运动范围
机器人的运动范围
2022-07-30 00:09:00 【龙崎流河】
题目:
地上有一个m行n列的方格,从坐标 [0,0] 到坐标 [m-1,n-1] 。一个机器人从坐标 [0, 0] 的格子开始移动,它每次可以向左、右、上、下移动一格(不能移动到方格外),也不能进入行坐标和列坐标的数位之和大于k的格子。例如,当k为18时,机器人能够进入方格 [35, 37] ,因为3+5+3+7=18。但它不能进入方格 [35, 38],因为3+5+3+8=19。请问该机器人能够到达多少个格子?
分析:
机器人如果想到达右下角,只需要右移和下移,同时要避免遇到相同的格子,因为在过程中会遇到障碍,左移和上移会走到重复的格子,重复的格子就不用算了,所以该题最好采用图的深度优先遍历,由于k的限制,需要自己创建一个函数,来计算方格坐标化成数字然后与k比较,如果k小于函数计算坐标的和,那么就不能通过。
代码:
public class MovingCount {
//深度优先遍历
int m;
int n;
int k;
boolean[][] visited;
public int movingCount(int m, int n, int k) {
this.m = m;
this.n = n;
this.k = k;
visited = new boolean[m][n];
return dfs(0,0);
}
private int dfs(int i, int j) {
if (i <0 || j <0 || i >=m || j>= n || visited[i][j] || k < sum(i)+sum(j)){
return 0;
}
visited[i][j] = true;
return 1 + dfs(i+1,j) + dfs(i,j+1);
}
private int sum(int x){
int res = 0;
while (x !=0){
res = res + x%10;
x = x/10;
}
return res;
}
}

边栏推荐
猜你喜欢
随机推荐
Adaptive feature fusion pyramid network for multi-classes agriculturalpest detection
头条号自媒体运营:如何在今日头条涨500+粉丝?
what is a .pro file in qt
C陷阱与缺陷 第5章 库函数 5.1 返回整数的getchar函数
Worthington弹性蛋白酶&透明质酸酶简介
MySQL事务隔离级别详解
Worthington优化技术:细胞定量
论文精读——YOLOv3: An Incremental Improvement
对数据库进行增删改查操作
2022/7/29 Exam Summary
Redis系列:高可用之Sentinel(哨兵模式)
一文解答web性能优化
NumPy(一)
新闻文本分类
全国双非院校考研信息汇总整理 Part.1
Worthington木瓜蛋白酶&胰凝乳蛋白酶&脱氧核糖核酸酶 I
2022年企业直播行业发展洞察
【集训DAY16】KC ‘ s Stars【dfs】
全国双非院校考研信息汇总整理 Part.8
MySQL事务(transaction) (有这篇就足够了..)






![CesiumJS ^ source read [0] 2022 - article directory and source engineering structure](/img/6a/0a446eb00fb73275897cbfb336e0b0.png)

