地上有一個(gè)m行n列的方格垢粮,從坐標(biāo) [0,0] 到坐標(biāo) [m-1,n-1] 采幌。一個(gè)機(jī)器人從坐標(biāo) [0, 0] 的格子開始移動(dòng)劲够,它每次可以向左、右休傍、上征绎、下移動(dòng)一格(不能移動(dòng)到方格外),也不能進(jìn)入行坐標(biāo)和列坐標(biāo)的數(shù)位之和大于k的格子。例如人柿,當(dāng)k為18時(shí)柴墩,機(jī)器人能夠進(jìn)入方格 [35, 37] ,因?yàn)?+5+3+7=18凫岖。但它不能進(jìn)入方格 [35, 38]江咳,因?yàn)?+5+3+8=19。請問該機(jī)器人能夠到達(dá)多少個(gè)格子哥放?
示例 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 一般用隊(duì)列
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;
}
}