*490. The Maze
https://leetcode.com/problems/the-maze/
solution
class Solution(object):
def hasPath(self, maze, start, destination):
n_row = len(maze)
n_col = len(maze[0])
queue = collections.deque([start])
visited = set()
visited.add(tuple(start))
while queue:
row, col = queue.popleft()
for dx, dy in [[0, -1], [0, 1], [-1, 0], [1, 0]]:
new_row, new_col = row, col
# "撞到墙才改变方向", 前面对方向循环,这里判断时加一个条件: 这个方向的maze一直为0, 一直同一个方向往下
while 0 <= new_row + dx < n_row and 0 <= new_col + dy < n_col and maze[new_row + dx][new_col + dy] == 0:
new_row += dx
new_col += dy
if [new_row, new_col] == destination:
return True
if (new_row, new_col) not in visited:
visited.add((new_row, new_col))
queue.append((new_row, new_col))
return False时间复杂度:O() 空间复杂度:O()
follow up
时间复杂度:O() 空间复杂度:O()
时间复杂度:O() 空间复杂度:O()
Last updated