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 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
| class Solution { class Step { public List<Step> walked = new LinkedList<Step>(); public int obstaclesCount = 0; public Step from = null; public final int row, column;
Step(int i, int j) { this.row = i; this.column = j; walked.add(this); }
Step(int i, int j, List<Step> walked, Step from) { this(i, j); this.from = from; this.walked.addAll(walked); }
public boolean canWalking(int x) { switch (x) { case 1: return true; case 2: return true; case 0: return true;
} return false; }
public int walking(int[][] grid) { int count = 0; if (grid[row][column] == -1) { System.out.println("-1"); return 0; } if (grid[row][column] == 2) { if (this.walked.size() + obstaclesCount == grid[0].length * grid.length) return 1;
return 0; } if (grid[row][column] == 0 || grid[row][column] == 1) { if (row > 0) { if (canWalking(grid[row - 1][column])) { Step top = new Step(row - 1, column, walked, this); if (!walked.contains(top)) { top.obstaclesCount = this.obstaclesCount; count += top.walking(grid); } } } if ((row + 1) < grid.length) { if (canWalking(grid[row + 1][column])) { Step bottom = new Step(row + 1, column, walked, this); if (!walked.contains(bottom)) { bottom.obstaclesCount = this.obstaclesCount; count += bottom.walking(grid); } } } if (column > 0) { if (canWalking(grid[row][column - 1])) {
Step left = new Step(row, column - 1, walked, this); if (!walked.contains(left)) { left.obstaclesCount = this.obstaclesCount; count += left.walking(grid); } } } if ((column + 1) < grid[0].length) { if (canWalking(grid[row][column + 1])) { Step right = new Step(row, column + 1, walked, this); if (!walked.contains(right)) { right.obstaclesCount = this.obstaclesCount; count += right.walking(grid); } } } } return count; }
@Override public boolean equals(Object obj) { if (obj instanceof Step) { Step step = (Step) obj; if (step.row == this.row && step.column == this.column) return true; } return false; }
}
public int uniquePathsIII(int[][] grid) { int rowMax = grid.length, columnMax = grid[0].length; int obstaclesCount = 0; Step start = null; for (int i = 0; i < rowMax; i++) { for (int j = 0; j < columnMax; j++) { if (grid[i][j] == 1) start = new Step(i, j); if (grid[i][j] == -1) obstaclesCount++; } }
if (start != null) { start.obstaclesCount = obstaclesCount; return start.walking(grid); }
return 0; } }
|