BFS解决迷宫问题


```python
"""
迷宫问题1:
    有如下迷宫,给定起始位置,和出口位置,怎么走出去?
"""

mat = [
    [0,0,0,0,0,0,0,0],
    [0,1,1,1,1,0,1,0],
    [0,0,0,0,1,0,1,0],
    [0,1,0,0,0,0,1,0],
    [0,1,0,1,1,0,1,0],
    [0,1,0,0,0,0,1,1],
    [0,1,0,0,1,0,0,0],
    [0,1,1,1,1,1,1,0]
]
start = [0,0]
end = [7,7]



def wrapped(mat):
    new_mat = [[1 for i in range(len(mat[0])+2)] for j in range(len(mat)+2)]
    for i in range(len(mat)):
        new_mat[i+1][1:-1] = mat[i]
    return new_mat
print(wrapped(mat))


new_mat = [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
           [1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
           [1, 0, 1, 1, 1, 1, 0, 1, 0, 1],
           [1, 0, 0, 0, 0, 1, 0, 1, 0, 1],
           [1, 0, 1, 0, 0, 0, 0, 1, 0, 1],
           [1, 0, 1, 0, 1, 1, 0, 1, 0, 1],
           [1, 0, 1, 0, 0, 0, 0, 1, 1, 1],
           [1, 0, 1, 0, 0, 1, 0, 0, 0, 1],
           [1, 0, 1, 1, 1, 1, 1, 1, 0, 1],
           [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]
new_start = [1,1,-1]
new_end = [8,8]

queue = [new_start]
# color
new_mat[new_start[0]][new_start[1]] = 1
trace = []
while queue:
    now_point = queue.pop(0)
    trace.append(now_point)
    if now_point[0] == new_end[0] and now_point[1] == new_end[1]:
        print("ok")
        break
    # up
    if new_mat[now_point[0]-1][now_point[1]] == 0:
        queue.append([now_point[0]-1, now_point[1], [now_point[0], now_point[1]]])
        new_mat[now_point[0]-1][now_point[1]] = 1

    # down
    if new_mat[now_point[0]+1][now_point[1]] == 0:
        queue.append([now_point[0]+1, now_point[1], [now_point[0], now_point[1]]])
        new_mat[now_point[0]+1][now_point[1]] = 1

    # left
    if new_mat[now_point[0]][now_point[1]-1] == 0:
        queue.append([now_point[0], now_point[1] -1, [now_point[0], now_point[1]]])
        new_mat[now_point[0] + 1][now_point[1] -1] = 1

    # right
    if new_mat[now_point[0]][now_point[1] + 1] == 0:
        queue.append([now_point[0], now_point[1] + 1, [now_point[0], now_point[1]]])
        new_mat[now_point[0]][now_point[1] + 1] = 1
print(trace)
route = {}
for i in trace:
    route[(i[0], i[1])] = i[2]
print(route)

rst = [new_end]
while True:
    p = route.get((rst[-1][0], rst[-1][1]))
    rst.append(p)
    if p == new_start[:2]:
        print("+++++++++++")
        break
print(rst)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值