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是目标位置,-1是不可达位置,0是可以走的位置,从起始位置开始,每一次只能往上下左右的某一个方向走一步,问有多少种方法,可以走到所有的0位置,且都只走一次,最终到达目标位置。
解题思路:
广度优先遍历。从1位置开始,每一次选择一个可以走到的、之前没有走过的位置,将其记录下来,然后进行递归。当走到2位置的时候,如果记录的位置数目等于0位置的数目,那么符合要求。
class Solution {
int[][] grid;
Set<Integer> visited = new HashSet<>();
int[][] dirs = new int[][]{{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
int row, col, total = 2;
int res = 0;
public void bfs(int i, int j){
if(grid[i][j] == 2){
if(visited.size() == total)
res++;
}
for(int[] dir : dirs){
int ni = i + dir[0], nj = j + dir[1];
if(ni > -1 && ni < row && nj > -1 && nj < col){
int pos = ni * col + nj;
if(!visited.contains(pos) && grid[ni][nj] != -1){
visited.add(pos);
bfs(ni, nj);
visited.remove(pos);
}
}
}
}
public int uniquePathsIII(int[][] grid) {
this.grid = grid;
row = grid.length;
if(row == 0)
return 0;
col = grid[0].length;
int x = -1, y = -1;
for(int i = 0; i < row; i++){
for(int j = 0; j < col; j++){
if(grid[i][j] == 0)
total++;
if(grid[i][j] == 1){
x = i;
y = j;
}
}
}
visited.add(x * col + y);
bfs(x, y);
return res;
}
}