题目如下:
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
解题思路:因为grid数据非常少,所以直接DFS/BFS即可得到答案。遍历grid的过程中记录每个节点是否已经遍历过,通过记录已经遍历了遍历节点的总数
代码如下:
class Solution(object): def uniquePathsIII(self, grid): """ :type grid: List[List[int]] :rtype: int """ import copy visit = [] count = 0 total = len(grid) * len(grid[0]) startx,starty = 0,0 for i in range(len(grid)): visit.append([0] * len(grid[i])) for j in range(len(grid[i])): if grid[i][j] == -1: count += 1 elif grid[i][j] == 1: startx,starty = i,j visit[startx][starty] = 1 queue = [(startx,starty,copy.deepcopy(visit),1)] res = 0 while len(queue) > 0: x,y,v,c = queue.pop(0) if grid[x][y] == 2 and c == total - count: res += 1 continue direction = [(-1,0),(1,0),(0,1),(0,-1)] for i,j in direction: if x + i >= 0 and x + i < len(grid) and y + j >= 0 and y + j < len(grid[0]) and v[x+i][y+j] == 0 and grid[x+i][y+j] != -1: v_c = copy.deepcopy(v) v_c[x+i][y+j] = 1 queue.append((x+i,y+j,v_c,c+1)) return res