地上有一个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
提示:
1 <= n,m <= 100
0 <= k <= 20
两种遍历方式DFS/BFS
//深度优先搜索dfs
class Solution {
int m,n;
boolean [][]visited;
public int movingCount(int m, int n, int k) {
this.m=m;
this.n=n;
visited=new boolean[m][n];
return dfs(0,0,k);
}
public int dfs(int i,int j,int k){
if(i>=m||j>=n
|| visited[i][j]
|| sum(i,j)>k
)return 0;
visited[i][j]=true;
return 1+dfs(i+1,j,k)+dfs(i,j+1,k);
}
public int sum(int i,int j){
int sum = 0;
while (i != 0) {
sum += i % 10;
i /= 10;
}
while (j != 0) {
sum += j % 10;
j /= 10;
}
return sum;
}
}
BFS
//广度优先搜索
class Solution {
public int movingCount(int m, int n, int k) {
boolean[][] visited = new boolean[m][n];
int[][] direct = {{1, 0}, {0, 1}};
int res = 0;
Queue<AbstractMap.SimpleEntry<Integer, Integer>> queue = new LinkedList<>();
queue.add(new AbstractMap.SimpleEntry<>(0, 0));
while (!queue.isEmpty()) {
AbstractMap.SimpleEntry<Integer, Integer> cor = queue.poll();
Integer x = cor.getKey();
Integer y = cor.getValue();
int sum = x / 10 + x % 10 + y / 10 + y % 10;
if (x < 0 || y < 0 || x >= m || y >= n || visited[x][y] || sum > k) {
continue;
}
visited[x][y] = true;
res++;
for (int i = 0; i < 2; i++) {
queue.add(new AbstractMap.SimpleEntry<>(x + direct[i][0], y + direct[i][1]));
}
}
return res;
}
}