publicintmovingCount(int m, int n, int k){ // case 1 int[][] map = newint[m][n]; for(int i=0; i<m; i++){ Arrays.fill(map[i], 1); } return dfs(map, k, 0, 0); }
privateintdfs(int[][] map, int k, int i, int j){ if (i<0 || i>=map.length || j<0 ||j>=map[0].length || sumPos(i, j) > k || map[i][j]!=1) { return0; } int temp = map[i][j]; map[i][j] = 0; return temp + dfs(map, k, i+1, j) + dfs(map, k, i, j+1); }
privateintsumPos(int a, int b){ if(a < 0 || b < 0) return -1; int res=0; while(a != 0) { res += a %10; a /=10; } while(b != 0) { res += b%10; b /= 10; } return res; } }
publicintmovingCount2(int m, int n, int k){ boolean[][] visited = newboolean[m][n]; int res = 0; Queue<int[]> queue = new LinkedList<>(); queue.add(newint[]{0,0}); while (queue.size() > 0) { int[] x = queue.poll(); int i = x[0], j = x[1]; if (i>=m || j>= n || get(i, j)>k || visited[i][j] == true) { continue; } visited[i][j] = true; res++; queue.add(newint[]{i+1, j}); queue.add(newint[]{i, j+1}); } return res; }