0980. Unique Paths III (H)
阿新 • • 發佈:2020-09-20
Unique Paths III (H)
題目
On a 2-dimensional grid
, there are 4 types of squares:
1
represents the starting square. There is exactly one starting square.2
represents the ending square. There is exactly one ending square.0
represents empty squares we can walk over.-1
represents obstacles that we cannot walk over.
Return the number of 4-directional walks from the starting square to the ending square, that walk over every non-obstacle square exactly once.
Example 1:
Input: [[1,0,0,0],[0,0,0,0],[0,0,2,-1]] Output: 2 Explanation: We have the following two paths: 1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2) 2. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2)
Example 2:
Input: [[1,0,0,0],[0,0,0,0],[0,0,0,2]] Output: 4 Explanation: We have the following four paths: 1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2),(2,3) 2. (0,0),(0,1),(1,1),(1,0),(2,0),(2,1),(2,2),(1,2),(0,2),(0,3),(1,3),(2,3) 3. (0,0),(1,0),(2,0),(2,1),(2,2),(1,2),(1,1),(0,1),(0,2),(0,3),(1,3),(2,3) 4. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2),(2,3)
Example 3:
Input: [[0,1],[2,0]]
Output: 0
Explanation:
There is no path that walks over every empty square exactly once.
Note that the starting and ending square can be anywhere in the grid.
Note:
1 <= grid.length * grid[0].length <= 20
題意
給定一個二維陣列,1表示起點,2表示終點,0表示可通行,-1表示不可通行。找到一條從起點到終點的路徑,使其能通過所有可通行的點,統計這樣的路徑的個數。
思路
直接暴力回溯就能AC。
程式碼實現
Java
class Solution {
private int count;
private int m, n;
private int[] iPlus = { -1, 0, 1, 0 };
private int[] jPlus = { 0, 1, 0, -1 };
public int uniquePathsIII(int[][] grid) {
m = grid.length;
n = grid[0].length;
int x = 0, y = 0;
int left = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] >= 0) {
left++;
}
if (grid[i][j] == 1) {
x = i;
y = j;
}
}
}
dfs(grid, x, y, left, new boolean[m][n]);
return count;
}
private void dfs(int[][] grid, int i, int j, int left, boolean visited[][]) {
if (grid[i][j] == 2 && left == 1) {
count++;
return;
}
visited[i][j] = true;
for (int x = 0; x < 4; x++) {
int nextI = i + iPlus[x];
int nextJ = j + jPlus[x];
if (isValid(grid, nextI, nextJ) && !visited[nextI][nextJ]) {
dfs(grid, nextI, nextJ, left - 1, visited);
}
}
visited[i][j] = false;
}
private boolean isValid(int[][] grid, int i, int j) {
return i >= 0 && i < m && j >= 0 && j < n && grid[i][j] != -1;
}
}