1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| public class Solution { private static boolean[][] visited; public int movingCount(int threshold, int rows, int cols) { visited = new boolean[rows][cols]; return helper(threshold, rows, cols, 0, 0); }
private int helper(int threshold, int rows, int cols, int curRow, int curCol) { if (curRow < 0 || curRow >= rows || curCol < 0 || curCol >= cols || visited[curRow][curCol] || !checkVerify(threshold, curRow, curCol)) return 0;
visited[curRow][curCol] = true; return 1 + helper(threshold, rows, cols, curRow + 1, curCol) + helper(threshold, rows, cols, curRow - 1, curCol) + helper(threshold, rows, cols, curRow, curCol + 1) + helper(threshold, rows, cols, curRow, curCol - 1); }
private boolean checkVerify(int k, int curRow, int curCol) { int sum = 0; while (curRow != 0 || curCol != 0) { sum += curCol % 10 + curRow % 10; if (sum > k) return false; curRow /= 10; curCol /= 10; } return sum <= k; } }
|