[13]机器人的运动范围
文章目录
题目
地上哟一个 m 行 n 列的方格。一个机器人从坐标(0,0)的格子开始移动,它每次可以向左、右、上、下移动一格但不能进入行坐标和列坐标的数位之和大于 k k k 的格子
例如,当 k 为18 时,机器人能够进入方格(35,37)因为 3 + 5 + 3 + 7 = 18 3+5+3+7=18 3+5+3+7=18,但不能进入方格(35,38),因为3+5+3+8=19
请问机器人能到达多少个格子?
思路
这是一个典型的宽度优先搜索问题,我们从 (0, 0) 点开始,每次朝上下左右四个方向扩展新的节点即可。
扩展时需要注意新的节点需要满足如下条件:
- 之前没有遍历过,这个可以用个 b o o l bool bool数组来判断;
- 没有走出边界;
- 横纵坐标的各位数字之和小于 k k k.
代码
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();
// 这个数被遍历 || 各位数之和>k【不符合要求跳出循环】
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;
}
};