public class Solution {
    public int movingCount(int threshold, int rows, int cols)
    {//rows是行数,row是行的坐标 列同理
        if(threshold < 0 || rows <= 0 || cols <= 0)
            return 0;
        boolean[] visited = new boolean[rows * cols];
        for(int i = 0;i < rows * cols;i++){
            visited[i] = false;
        }
        int count = movingCountCore(threshold, rows, cols, 0, 0, visited);
        return count; 
    }
    
    public int movingCountCore(int threshold, int rows, int cols, int row, int col, boolean[] visited){
        int count = 0;
        //如果能够通过检验,则可以访问,visited变为true,然后count累加,继续在这个点的上下左右位置进行检测
        if(checkNum(threshold, rows, cols, row, col, visited)){
            visited[row * cols + col] = true;
            count = 1 + movingCountCore(threshold, rows, cols ,row, col + 1, visited)
                + movingCountCore(threshold, rows, cols, row, col - 1, visited)
                + movingCountCore(threshold, rows, cols, row + 1, col, visited)
                + movingCountCore(threshold, rows, cols, row - 1, col, visited);
        }
        return count;
    }
    //这道题的主题,看两个数的位数相加是否小于等于阈值(threshold),检验过了则visited成为true
    public boolean checkNum(int threshold, int rows, int cols, int row, int col, boolean[] visited){
        if(row >= 0 && row < rows && col >= 0 && col < cols && getSum(row) + getSum(col) <= threshold && !visited[row * cols + col]){
            return true;
        }
        return false;
    }
    public int getSum(int num){//求出每个数字位数相加和的方法
        int sum = 0;
        while(num > 0){
            sum += num % 10;
            num = num / 10;
        }
        return sum;
    }
}