题目
地上有一个 m 行和 n 列的方格,横纵坐标范围分别是 0∼m−1 和 0∼n−1。
一个机器人从坐标 (0,0) 的格子开始移动,每一次只能向左,右,上,下四个方向移动一格。
但是不能进入行坐标和列坐标的数位之和大于 k 的格子。
请问该机器人能够达到多少个格子?
注意
:
- 0<=m<=50
- 0<=n<=50
- 0<=k<=100
示例
- 示例1
- 输入:k=7, m=4, n=5
- 输出:20
- 示例2
- 输入:k=18, m=40, n=40
- 输出:1484
解释
:当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。
代码
解法:BFS
class Solution {
public:
int get_sum(pair<int, int> p) {
int s = 0;
while (p.first) {
s += p.first % 10;
p.first /= 10;
}
while (p.second) {
s += p.second % 10;
p.second /= 10;
}
return s;
}
int movingCount(int threshold, int rows, int cols)
{
if (!rows || !cols) return 0;
queue<pair<int,int>> q;
vector<vector<bool>> st(rows, vector<bool>(cols, false));
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1}; // 上右下左
int res = 0;
q.push({0, 0});
while (q.size()) {
auto t = q.front();
q.pop();
if (st[t.first][t.second] || get_sum(t) > threshold) continue; // 已访问或者大于门限值,不添加
res ++ ;
st[t.first][t.second] = true;
for (int i = 0; i < 4; i ++ ) {
int x = t.first + dx[i], y = t.second + dy[i];
if (x >= 0 && x < rows && y >= 0 && y < cols) q.push({x, y});
}
}
return res;
}
};
代码分析
:1、刚开始我以为遍历一下矩阵找出范围内的坐标的数量就可以,其实这是漏掉了一些条件。代码
class Solution {
public:
int calSum(int a){
return a/10 + a%10;
}
int movingCount(int threshold, int rows, int cols)
{
int cnt = 0;
for(int i = 0; i < rows; i++){
for(int j = 0; j < cols; j++){
if((calSum(i)+calSum(j)) <= threshold){
cnt++;
}
}
}
return cnt;
}
};
错误的原因
:
- 机器人不能闪现,每一次只能向左,右,上,下四个方向移动一格。
- 机器人不能进入行坐标和列坐标的
数位之和
大于 k 的格子。把坐标的数位之和作为边界条件,这就导致有一些坐标在规定范围内,但是机器人不可达。
2、所以还是选择了宽搜(BFS),因为在处理较多数据的时候,DFS容易栈溢出。先看辅助函数:
int get_sum(pair<int, int> p) {
int s = 0;
while (p.first) {
s += p.first % 10;
p.first /= 10;
}
while (p.second) {
s += p.second % 10;
p.second /= 10;
}
return s;
}
get_sum(pair<int, int> p)
功能是拿到横纵坐标的数位之和。接着看movingCount(int threshold, int rows, int cols)
里的代码:
if (!rows || !cols) return 0;
如果给的矩阵的横纵坐标有一个为 0 的,那么就是没有数据。
queue<pair<int,int>> q;
BFS 借助队列,DFS 借助栈。队列里面是一个坐标,用键值对来表示。
vector<vector<bool>> st(rows, vector<bool>(cols, false));
st 为访问矩阵,为 true 代表已访问,false 代表未访问。(bool 类型 vector 初始化不给参数,默认为 false)
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1}; // 上右下左
dx[ ] dy[ ] 为方向矩阵(上右下左)
while (q.size()) {
auto t = q.front();
q.pop();
if (st[t.first][t.second] || get_sum(t) > threshold) continue; // 已访问或者大于门限值,不添加
res ++ ;
st[t.first][t.second] = true;
for (int i = 0; i < 4; i ++ ) {
int x = t.first + dx[i], y = t.second + dy[i];
if (x >= 0 && x < rows && y >= 0 && y < cols) q.push({x, y});
}
}
先从一个起点出发,入队,弹出,判断是否已访问或者大于门限值。如果不符合条件,直接跳过;如果符合条件(未访问并且不大于门限值),标志已访问,计数加一,再将其四个方向的坐标依次添加进队列(判断是否在边界内)。
逗号表达式
: 从左到右逐个计算;逗号表达式作为一个整体,它的值为最后一个表达式的值;逗号表达式的优先级别在所有运算符中最低。
例如:
*(3+5,6+8)的值是14
(a=35,a*4)的值是60
题目
:机器人的运动范围