0%

Leetcode980-uniquePathsIII

Description

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

Example 1:

1
2
3
4
5
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:
1
2
3
4
5
6
7
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:
1
2
3
4
5
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.

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
class Solution {
private int res = 0;
private int[][] dir = new int[][]{{1, 0},{-1, 0},{0, 1},{0, -1}};
public int uniquePathsIII(int[][] grid) {
int numOb = 0;
int[] start = new int[2];
int[] end = new int[2];
for (int i = 0; i < grid.length; i++)
for (int j = 0; j < grid[0].length; j++){
if (grid[i][j] == -1) numOb++;
if (grid[i][j] == 1){
start[0] = i;
start[1] = j;
}
}

boolean[][] visited = new boolean[grid.length][grid[0].length];
dfs(grid, start[0], start[1], visited, numOb, 1);

return res;
}

private void dfs(int[][] grid, int x, int y, boolean[][] visited, int numOb, int len){
if (grid[x][y] == 2){
if (len == grid.length * grid[0].length - numOb)
res ++;
return;
}
visited[x][y] = true;
for (int i = 0; i < 4; i++){
int nx = x + dir[i][0];
int ny = y + dir[i][1];
if (nx >= 0 && nx < grid.length && ny >= 0 && ny < grid[0].length && !visited[nx][ny] && grid[nx][ny] != -1){
dfs(grid, nx, ny, visited, numOb, len + 1);
}
}
visited[x][y] = false;
}
}