数据结构-实例代码

栈的应用-迷宫问题

from collections import deque

否则找出当前方块的四个相邻的方块中可以走的方块，全部进队。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,y+1),  #右
lambda x,y:(x+1,y),  #下
lambda x,y:(x,y-1),  #左
]

def solve_maze(x1, y1, x2, y2):　　"""基于栈实现"""
stack = []
stack.append((x1,y1))
maze[x1][y1] = 2
while len(stack) > 0:   # 当栈不空循环
cur_node = stack[-1]
if cur_node == (x2,y2): #到达终点
for p in stack:
print(p)
return True
for dir in dirs:
next_node = dir(*cur_node)
if maze[next_node[0]][next_node[1]] == 0:   #找到一个能走的方向
stack.append(next_node)
maze[next_node[0]][next_node[1]] = 2  # 2表示已经走过的点
break
else: #如果一个方向也找不到
stack.pop()
else:
print("无路可走")
return False

def solve_maze2(x1,y1,x2,y2):    """基于队列来实现"""
queue = deque()
path = []    # 记录出队之后的节点
queue.append((x1,y1,-1))
maze[x1][y1] = 2
while len(queue) > 0:
cur_node = queue.popleft()
path.append(cur_node)
if cur_node[0] == x2 and cur_node[1] == y2:  #到终点
real_path = []
x,y,i = path[-1]
real_path.append((x,y))
while i >= 0:
node = path[i]
real_path.append(node[0:2])
i = node[2]
real_path.reverse()
for p in real_path:
print(p)
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]] = 2 # 标记为已经走过
else:
print("无路可走")
return False

solve_maze2(1,1,8,8)          #输入起点的位置和终点的位置

。。。。。。。。。。有时间更新

posted @ 2018-02-02 20:00 前方、有光 阅读(...) 评论(...) 编辑 收藏