版权声明:所有的博客都是个人笔记,交流可以留言。未经允许,谢绝转载。。。 https://blog.csdn.net/qq_35976351/article/details/88639380
题目描述
地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
解题思路
深度优先或者宽度优先。在这里使用了宽度优先BFS策略。注意一个坑,如果只有一个格子,需要返回1;如果多于1个格子,那么(0,0)这个点不算。
AC代码
class Solution {
public:
int movingCount(int threshold, int rows, int cols) {
if (threshold < 0 || rows * cols <= 0) { // 输入不合法~~删除线格式~~
return 0;
}
if (rows * cols == 1) { // 一个格子单独处理
return 1;
}
memset(visited, 0, sizeof(visited));
int res = -1;
K = threshold;
queue<Pos> que;
que.emplace(Pos(0, 0));
while (!que.empty()) {
auto p = que.front();
que.pop();
++res;
for (int i = 0; i < 4; ++i) {
int x = p.x + offset[i][0];
int y = p.y + offset[i][1];
if (x >= 0 && x < rows && y >= 0 && y < cols
&& !visited[x][y] && Access(x, y)) {
visited[x][y] = true;
que.emplace(Pos(x, y));
}
}
}
return res;
}
private:
struct Pos {
int x, y;
Pos(int _x = 0, int _y = 0) : x(_x), y(_y) {}
};
bool Access(int x, int y) {
int s = 0;
while (x != 0) {
s += x % 10;
x /= 10;
}
while (y != 0) {
s += y % 10;
y /= 10;
}
if (s <= K)
return true;
return false;
}
int offset[4][2] = { {0,1}, {0,-1},{1,0}, {-1,0} };
bool visited[1000][1000];
int K{ 0 };
int cnt{ 0 };
};