0%

Unique Paths III

Question

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)

Solution

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
/*
@param: int[][] grid
@return: int
Algorithm: 常规DFS+backtracking
*/
int res, todo = 1, sx, sy, ex, ey, row, col;
public int uniquePathsIII(int[][] grid) {
row = grid.length;
col = grid[0].length;
if (row == 0 || col == 0) {
return 0;
}
res = 0;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (grid[i][j] == 0) {
todo++;
}else if (grid[i][j] == 1) {
sx = i;
sy = j;
}else if (grid[i][j] == 2) {
ex = i;
ey = j;
}
}
}
dfs(sx, sy, grid);
return res;
}

public void dfs(int x, int y, int[][] grid) {
if (x < 0 || y < 0 || x >= row || y >= col || grid[x][y] < 0) {
return;
}
if (x == ex && y == ey ) {
if (todo == 0){
res++;
}
return;
}
todo--;
grid[x][y] = -2;
dfs(x+1,y,grid);
dfs(x-1,y,grid);
dfs(x,y+1,grid);
dfs(x,y-1,grid);
todo++;
grid[x][y] = 0;
}