地上有一个m行n列的方格,从坐标 [0,0] 到坐标 [m-1,n-1] 。一个机器人从坐标 [0, 0] 的格子开始移动,它每次可以向左、右、上、下移动一格(不能移动到方格外),也不能进入行坐标和列坐标的数位之和大于k的格子。例如,当k为18时,机器人能够进入方格 [35, 37] ,因为3+5+3+7=18。但它不能进入方格 [35, 38],因为3+5+3+8=19。请问该机器人能够到达多少个格子?
示例 1:
输入:m = 2, n = 3, k = 1
输出:3
示例 2:
输入:m = 3, n = 1, k = 0
输出:1
//dfs
class Solution {
private int m;
private int n;
private int k;
boolean[][] visited;
public int movingCount(int m, int n, int k) {
visited = new boolean[m][n];
this.m = m;
this.n = n;
this.k = k;
return dfs(0,0);
}
public int dfs(int x, int y){
if(x >= m || y >= n || visited[x][y] || sum(x,y) > k){
return 0;
}
visited[x][y] = true;
return 1 + dfs(x+1,y) + dfs(x, y+1);
// return 1 + dfs(x,y+1);
}
public int sum(int x,int y){
int s = 0;
while(x != 0){
s += x % 10;
x /= 10;
}
while(y != 0){
s += y % 10;
y /= 10;
}
return s;
}
}
//bfs bfs 一般用队列
class Solution {
public int movingCount(int m, int n, int k) {
Queue<int[]> queue = new LinkedList<>();
boolean[][] visited = new boolean[m][n];
// int[] start = {0,0};
queue.offer(new int[]{0,0});
int count = 0;
while(!queue.isEmpty()){
int[] move = queue.poll();
int x = move[0], y = move[1];
if(x >= m || y >= n || sum(x,y) > k || visited[x][y]) continue;
visited[x][y] = true;
count++;
queue.offer(new int[]{x+1,y});
queue.offer(new int[]{x,y+1});
// if(x+1 < m && y < n && !visited[x+1][y] && sum(x+1,y) <= k){
// queue.offer(new int[]{x+1,y});
// }
// if(x < m && y+1 < n && !visited[x][y+1] && sum(x,y+1) <= k){
// queue.offer(new int[]{x,y+1});
// }
}
return count;
}
public int sum(int x, int y){
int rs = 0;
while(x>0){
rs += x% 10;
x /= 10;
}
while(y > 0){
rs += y % 10;
y /= 10;
}
return rs;
}
}