题目描述
地上有一个rows行和cols列的方格。坐标从 [0,0] 到 [rows-1,cols-1]。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于threshold的格子。 例如,当threshold为18时,机器人能够进入方格[35,37],因为3+5+3+7 = 18。但是,它不能进入方格[35,38],因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
范围:
1 <= rows, cols<= 100
0 <= threshold <= 20
示例1
输入
1,2,3
返回值
3
示例2
输入
0,1,3
返回值
1
示例3
输入
10,1,100
返回值
29
说明
[0,0],[0,1],[0,2],[0,3],[0,4],[0,5],[0,6],[0,7],[0,8],[0,9],[0,10],[0,11],[0,12],[0,13],[0,14],[0,15],[0,16],[0,17],[0,18],[0,19],[0,20],[0,21],[0,22],[0,23],[0,24],[0,25],[0,26],[0,27],[0,28] 这29种,后面的[0,29],[0,30]以及[0,31]等等是无法到达的
示例4
输入
5,10,10
返回值
21
代码:
import java.util.*;
public class Solution {
public int movingCount(int threshold, int rows, int cols) {
int[] dx = {0, 1, 0, -1};
int[] dy = {1, 0, -1, 0};
boolean[][] mark = new boolean[rows][cols];
mark[0][0] = true;
Queue<int[]> que = new LinkedList<>();
que.add(new int[]{0,0});
while (!que.isEmpty()){
int[] cur = que.poll();
for (int i = 0; i < 4; i++) {
int x = cur[0] + dx[i];
int y = cur[1] + dy[i];
if(x >= 0 && x < rows && y >= 0 && y < cols && !isOver(threshold,x,y) && !mark[x][y]){
que.add(new int[]{x,y});
mark[x][y] = true;
}
}
}
int count = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if(mark[i][j]){
count++;
}
}
}
return count;
}
private boolean isOver(int k,int x,int y) {
int res = 0;
while (x > 0){
res += x % 10;
x /= 10;
}
while (y > 0){
res += y % 10;
y /= 10;
}
return res > k;
}
}
思路概述:
一个mark数组记录是否能到达过,用一个队列记录能达到的坐标,只要队列不为空,就弹出一个坐标,并判断该坐标的上下左右是否能到达,能到达则入队。最后遍历mark数组,为true的点则代表可以到达的