n = 8
1 2 3 4 5 6 7 8 * 2 3 4 5 6 7 8
2 3 4 5 6 7 8 * * 3 4 5 6 7 8
3 4 5 6 7 8 * * * 4 5 6 7 8
.....
8 * * * * * * * *
2 3 4 5 6 7 8
3 4 5 6 7 8
4 5 6 7 8
.....
不存在
1 2 3
1 true false true
2 true true true
此种结构,(2,1)的值不可能同时大于 (1,1),(1,3),(2,2)
同理,不存在
true true
flase true
true true
因此,遍历的时候只需向下,向右遍历即可
class Solution {
int sum = 1;
int m,n,k;
public int movingCount(int m, int n, int k) {
this.m = m;
this.n = n;
this.k = k;
if(k == 0) return 1;
boolean[][] flat = new boolean[m][n];
flat[0][0] = true;
dfs(flat, 0,1);
dfs(flat, 1,0);
return sum;
}
private void dfs(boolean[][] flat, int i, int j){
if(i >= this.m || j >= this.n || flat[i][j] || (get(i) + get(j) > k)) return;
sum ++;
flat[i][j] = true;
dfs(flat, i, j + 1);
dfs(flat, i + 1, j);
}
private int get(int num){
int sum = 0;
while(num / 10 != 0){
sum += num % 10;
num /= 10;
}
sum += num % 10;
return sum;
}
}