题目来源(acwing - 24):
地上有一个 mm 行和 nn 列的方格,横纵坐标范围分别是 0∼m−10∼m−1 和 0∼n−10∼n−1。
一个机器人从坐标 (0,0)(0,0) 的格子开始移动,每一次只能向左,右,上,下四个方向移动一格。
但是不能进入行坐标和列坐标的数位之和大于 kk 的格子。
请问该机器人能够达到多少个格子?
注意:
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。
解题:
struct queue
{
int x;
int y;
}que[2501]; //队列结构体,地图最多50 * 50
int book[51][51]; //标记
int is(int t, int x, int y) //
{
int a = 0, b = 0;
while (x || y) {
a += x % 10;
x /= 10;
b += y % 10;
y /= 10;
}
return (a + b) <= t;
}
int movingCount(int threshold, int rows, int cols)
{
int head, tail, tx, ty;
int chan[4][2] = { {1,0},{0,1},{0,-1},{-1,0} }; //上,下,左, 右 方向;
if (!rows || !cols) return 0; //图 为空,返回0;
head = tail = 1;
que[tail].x = 0;
que[tail++].y = 0;
book[0][0] = 1; //初始化队列,将0, 0点加入队列并标记;
while (head < tail) {
for (int i = 0; i <= 3; i++) { //循环队列头的临近节点
tx = que[head].x + chan[i][0];
ty = que[head].y + chan[i][1];
if (tx < 0 || tx > rows - 1 || ty < 0 || ty > cols - 1)
continue; //判断是否越界
if (is(threshold,tx,ty) && book[tx][ty] == 0) {
book[tx][ty] = 1;//符合条件加入队列
que[tail].x = tx;
que[tail++].y = ty;
}
}
head++;
}
return tail - 1; //加入队列有多少个就是多少个;
}