public class Solution { int max = 0; int count = 0; int r = 0; int c = 0; boolean[][] flag; public int movingCount(int threshold, int rows, int cols) { max = threshold; r = rows; c = cols; flag = new boolean[rows][cols]; dfs(0,0); return count; } public void dfs(int i,int j){ if(i >= r || i < 0 || j >= c || j < 0 || flag[i][j]){ return; } int row = 0; int a = i; int b = j; int column = 0; while(a != 0){ row += a % 10; a /= 10; } while(b != 0){ column += b % 10; b /= 10; } if(row + column > max){ return; } flag[i][j] = true; count++; dfs(i + 1,j); dfs(i - 1,j); dfs(i , j + 1); dfs(i,j - 1); } }