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 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
| public class Jz13_3 {
public static void main(String[] args) { System.out.println(new Jz13_3().movingCount(1, 2, 3)); System.out.println(new Jz13_3().movingCount(0, 1, 3)); System.out.println(new Jz13_3().movingCount(10, 1, 100)); System.out.println(new Jz13_3().movingCount(5, 10, 10)); System.out.println(new Jz13_3().movingCount(18, 36, 38)); System.out.println(new Jz13_3().movingCount(15, 100, 100)); }
public int movingCount(int threshold, int rows, int cols) { if (rows == 0 || cols == 0) { return 0; }
int movingCount = 0; boolean[][] arr = new boolean[rows][cols];
Stack<Pair<Integer, Integer>> stack = new Stack<>(); stack.push(new Pair<>(0, 0));
while (!stack.isEmpty()) { final Pair<Integer, Integer> pop = stack.pop(); final Integer x = pop.getKey(); final Integer y = pop.getValue(); arr[x][y] = true; movingCount++;
if (border(x + 1, y, rows, cols) && reachable(x + 1, y, threshold) && !arr[x + 1][y]) { stack.push(new Pair<>(x + 1, y)); arr[x + 1][y] = true; }
if (border(x, y + 1, rows, cols) && reachable(x, y + 1, threshold) && !arr[x][y + 1]) { stack.push(new Pair<>(x, y + 1)); arr[x][y + 1] = true; }
if (border(x - 1, y, rows, cols) && reachable(x - 1, y, threshold) && !arr[x - 1][y]) { stack.push(new Pair<>(x - 1, y)); arr[x - 1][y] = true; }
if (border(x, y - 1, rows, cols) && reachable(x, y - 1, threshold) && !arr[x][y - 1]) { stack.push(new Pair<>(x, y - 1)); arr[x][y - 1] = true; }
}
return movingCount; }
private boolean border(int i, int j, int rows, int cols) { return i >= 0 && i < rows && j >= 0 && j < cols; }
private boolean reachable(int i, int j, int threshold) { final int sum = getSum(i) + getSum(j); return sum <= threshold; }
private int getSum(int a) { int sum = 0; while (a > 0) { sum += a % 10; a = a / 10; } return sum; }
public static class Pair<K, V> {
private final K key; private final V value;
public K getKey() { return key; }
public V getValue() { return value; }
public Pair(K key, V value) { this.key = key; this.value = value; } } }
|