public class Solution { public int movingCount(int threshold, int rows, int cols) { boolean[][] v = new boolean[rows + 1][cols + 1]; return helper(threshold, 0, 0, v, rows, cols); } public int helper(int threshold, int i, int j, boolean[][] v, int rows, int cols){ if(i < 0 || i >= rows || j < 0 || j >= cols || v[i][j] || numSum(i) + numSum(j) > threshold) { return 0; } v[i][j] = true; return helper(threshold, i + 1, j, v, rows, cols) + helper(threshold, i - 1, j, v, rows, cols) + helper(threshold, i, j + 1, v, rows, cols) + helper(threshold, i, j - 1, v, rows, cols) + 1; } public int numSum(int num){ int sum = 0; while(num != 0){ int k = num%10; sum += k; num /= 10; } return sum; } }