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
| public class MovingCount {
public int movingCount(int threshold, int rows, int cols) { int[][] flag = new int[rows][cols]; return movingCount(0, 0, rows, cols, flag, threshold); }
private int movingCount(int i, int j, int rows, int cols, int[][] flag, int threshold) { if (i < 0 || j < 0 || i >= rows || j >= cols || numSum(i) + numSum(j) > threshold || flag[i][j] == 1) { return 0; } flag[i][j] = 1; return movingCount(i - 1, j, rows, cols, flag, threshold) + movingCount(i, j - 1, rows, cols, flag, threshold) + movingCount(i, j + 1, rows, cols, flag, threshold) + movingCount(i + 1, j, rows, cols, flag, threshold) + 1; }
private int numSum(int num) { int sum = 0; while (num != 0) { sum += num % 10; num = num / 10; } return sum; }
}
|