迷宫问题
maze = [
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 0, 0, 1, 0, 0, 0, 1, 0, 1],
[1, 0, 0, 1, 0, 0, 0, 1, 0, 1],
[1, 0, 0, 0, 0, 1, 1, 0, 0, 1],
[1, 0, 1, 1, 1, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 1, 0, 0, 0, 0, 1],
[1, 0, 1, 0, 0, 0, 1, 0, 0, 1],
[1, 0, 1, 1, 1, 0, 1, 1, 0, 1],
[1, 1, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
]
dirs = [
lambda x, y: (x + 1, y),
lambda x, y: (x - 1, y),
lambda x, y: (x, y + 1),
lambda x, y: (x, y - 1),
]
def maze_path_queue(x1: int, y1: int, x2: int, y2: int):
"""
走出迷宫,采用bfs广度优先搜索。
时间复杂度: O(n)
空间复杂度: O(n)
:param x1: 入口x
:param y1: 入口y
:param x2: 出口x
:param y2: 出口y
:return: [] 踪迹
"""
def print_r(path_):
"""
打印路径
:param path_: 走过的路径
:return:
"""
cur_node_ = path_[-1]
real_path = []
while cur_node_[2] != -1:
real_path.append(cur_node_[0:2])
cur_node_ = path_[cur_node_[2]]
real_path.append(cur_node_[0:2])
real_path.reverse()
for node in real_path:
print(node)
queue = collections.deque()
queue.append((x1, y1, -1))
path = []
while queue:
cur_node = queue.popleft()
path.append(cur_node)
if cur_node[0] == x2 and cur_node[1] == y2:
print_r(path)
return True
for dir in dirs:
next_node = dir(cur_node[0], cur_node[1])
if maze[next_node[0]][next_node[1]] == 0:
queue.append((next_node[0], next_node[1], len(path) - 1))
maze[next_node[0]][next_node[1]] = 3
print("没有路")
return False
if __name__ == "__main__":
maze_path_queue(1, 1, 8, 8)