classSolution{ publicintmovingCount(int m, int n, int k){ boolean[][] visit = newboolean[m][n]; return dfs(m, n, k, 0, 0, visit); }
publicintdfs(int m, int n, int k, int i, int j, boolean[][] visit){ if (i < 0 || i >= m || j < 0 || j >= n || visit[i][j] || forbid(i, j, k)) { return0; } visit[i][j] = true; return1 + dfs(m, n, k, i + 1, j, visit) + dfs(m, n, k, i, j + 1, visit); }
publicbooleanforbid(int i, int j, int k){ int sum = 0; while (i > 0 || j > 0) { sum += i % 10; sum += j % 10; i /= 10; j /= 10; } return sum > k; } }
classSolution{ publicintmovingCount(int m, int n, int k){ LinkedList<int[]> queue = new LinkedList<>(); boolean[][] visit = newboolean[m][n]; queue.add(newint[]{0, 0}); int count = 0; while (!queue.isEmpty()) { int size = queue.size(); for (int i = 0; i < size; i++) { int[] pos = queue.poll(); int r = pos[0], c = pos[1]; if (r < 0 || r >= m || c < 0 || c >= n || visit[r][c] || forbid(r, c, k)) { continue; } visit[r][c] = true; queue.add(newint[]{r + 1, c}); queue.add(newint[]{r, c + 1}); count++; } } return count; }
publicbooleanforbid(int i, int j, int k){ int sum = 0; while (i > 0 || j > 0) { sum += i % 10; sum += j % 10; i /= 10; j /= 10; } return sum > k; } }