当前位置:网站首页>剑指 Offer 13. 机器人的运动范围 (BFS)
剑指 Offer 13. 机器人的运动范围 (BFS)
2022-06-29 17:26:00 【华为云】
解锁BFS
题目:
地上有一个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。请问该机器人能够到达多少个格子?
输入:m = 2, n = 3, k = 1
输出:3
1 <= n,m <= 100
0 <= k <= 20
代码
class Solution {public: int cnt=1; int k; int visit[100][100]; int d[4][2] = {{0,1}, {0,-1}, {1,0}, {-1,0}}; //四个方向 int m,n; int getNumsSum(int x,int y){ //计算行坐标和列坐标的数位之和 int sum=0; while(x){ sum+=(x%10); x/=10; } while(y){ sum+=(y%10); y/=10; } return sum; } void bfs(int i,int j){ //从第i,j个格子开始 queue<pair<int,int> > q; q.push({i,j}); visit[i][j]=1; while(q.size()){ pair<int,int> t=q.front(); q.pop(); int tx=t.first,ty=t.second; for (int i = 0; i < 4; i++) { //扩展(tx,ty)的4个邻居 int nx = tx + d[i][0], ny = ty + d[i][1]; if(nx< m && nx>=0 && ny>=0 && ny<n && visit[nx][ny]==0 && getNumsSum(nx,ny)<=k) { visit[nx][ny] = 1; //注意:这一句必不可少 cnt++; q.push({nx, ny}); } } } } int movingCount(int m, int n, int k) { this->k=k; this->m=m; this->n=n; bfs(0,0); return cnt; }};边栏推荐
- 线段树、树状数组模板(复制粘贴确实好用)
- Use SSH to pull codes
- Development of freedom free agreement pledge mining system
- 腾讯云发布自动化交付和运维产品Orbit,推动企业应用全面云原生化
- 使用 SSH 方式拉取代码
- 2022年软件评测师考试大纲
- R language ggplot2 visualization: use the patchwork package (directly use the plus sign +) to horizontally combine a ggplot2 visualization result and a plot function visualization result to form the f
- linux中mysql 1045错误如何解决
- Custom handlerinterceptor interceptor for user authentication
- 在线文本数字识别列表求和工具
猜你喜欢

为什么信息化 ≠ 数字化?终于有人讲明白了

mysql查询视图命令是哪个

如何创建虚拟形象

函数计算异步任务能力介绍 - 任务触发去重

Viewing splitchunks code segmentation from MPX resource construction optimization

自动收售报机

NAACL 2022 | 机器翻译SOTA模型的蒸馏

基于C语言开发实现的一个用户级线程库

Mysql中锁的使用场景是什么

Collaborative development of epidemic home outsourcing project 𞓜 community essay solicitation
随机推荐
Pancakeswap Technology: development principle of gripper robot system
外部自动(PLC启动机器人)
Redis bloom filter and cuckoo filter
About Kali using xshell connection
NAACL 2022 | 机器翻译SOTA模型的蒸馏
Automatic vending machine
卷妹带你学数据库---5天冲刺Day4
The aggregate function in the epidisplay package of R language divides numerical variables into different subsets based on factor variables, and calculates the summary statistics and aggregate data. W
Bags of Binary Words for Fast Place Recognition in Image Sequenc
序列检测器
How MySQL queries character set codes of tables
深圳内推 | 深圳计算科学研究院招聘机器学习助理工程师(校招)
R语言dplyr包filter函数通过组合逻辑(与逻辑)过滤dataframe数据中的数据、其中一个字段的内容等于指定向量中的其中一个,并且另外一个字段值大于某一阈值
How to use interrupt
First batch! Tencent cloud's ability to pass the solution of the government affairs collaboration platform of the China Academy of ICT
关于harbor私有仓库忘记登录密码
Online sql to CSV tool
L'intercepteur handlerinterceptor personnalisé permet l'authentification de l'utilisateur
自学结构体(小甲鱼c语言)
如何在 PowerPoint 中向幻灯片添加 SmartArt?