每次向右或者向下运动即可 使用回溯法 if中有flag判断是因为反正有格子重复计算 使用取模 除法 来实现位数相加
public class Solution {
int count = 0;
public int movingCount(int threshold, int rows, int cols) {
boolean[][] flag = new boolean[rows][cols];
dfs(threshold, rows, cols, 0,0,flag);
return count;
}
private void dfs(int threshold, int rows, int cols,int i,int j,boolean[][] flag){
if(i >= rows || j >= cols || flag[i][j] || sum(i)+sum(j) > threshold){
return;
}
flag[i][j] = true;
count++;
dfs(threshold, rows, cols, i+1,j,flag);
dfs(threshold, rows, cols, i,j+1,flag);
}
private int sum(int threshold){
int sum = 0;
while(threshold != 0){
sum += threshold%10;
threshold /= 10;
}
return sum;
}
}

京公网安备 11010502036488号