使用递归,判断所有的点机器人是否可达即可
public class Solution { public int movingCount(int threshold, int rows, int cols) { int[][] flag = new int[rows][cols]; /*记录已经走过的点*/ return helper(0,0,rows,cols,flag,threshold); } public int helper(int i, int j, int rows, int cols, int[][] flag, int threshold){ if(i < 0 || i >= rows || j < 0 || j >= cols || flag[i][j] == 1 || numSum(i)+numSum(j) > threshold) return 0; flag[i][j] = 1; return helper(i+1,j,rows,cols,flag,threshold)+helper(i-1,j,rows,cols,flag,threshold)+ helper(i,j+1,rows,cols,flag,threshold)+helper(i,j-1,rows,cols,flag,threshold)+1; } // 计算坐标的数位和 public int numSum(int num){ int sum = 0; while(num > 0){ sum += num%10; num /= 10; } return sum; } }