publicintmovingCount(int m, int n, int k){ used = newboolean[m][n]; dfs(0, 0, k, m, n); return res; }
privatevoiddfs(int i, int j, int k, int m, int n){ if (i < 0 || i >= m || j < 0 || j >= n || used[i][j] || calculate(i) + calculate(j) > k) { return; } used[i][j] = true; res++; dfs(i + 1, j, k, m, n); dfs(i - 1, j, k, m, n); dfs(i, j + 1, k, m, n); dfs(i, j - 1, k, m, n); }
privateintcalculate(int x){ int ans = 0; while (x != 0) { ans += x % 10; x = x / 10; } return ans; }
publicintmovingCount(int m, int n, int k){ used = newboolean[m][n]; dfs(0, 0, k, m, n); return res; }
privatevoidbfs(int i, int j, int k, int m, int n){ Queue<int[]> queue = new LinkedList<>(); queue.add(newint[]{i, j}); while (!queue.isEmpty()) { int[] pos = queue.poll(); int x = pos[0]; int y = pos[1]; if (x >= 0 && x < m && y >= 0 && y < n && (calculate(x) + calculate(y) <= k) && !used[x][y]) { used[x][y] = true; res++; queue.add(newint[]{x + 1, y}); queue.add(newint[]{x - 1, y}); queue.add(newint[]{x, y + 1}); queue.add(newint[]{x, y - 1}); } } }
privateintcalculate(int x){ int ans = 0; while (x != 0) { ans += x % 10; x = x / 10; } return ans; }