python求解迷宫问题

59 篇文章 0 订阅
13 篇文章 0 订阅

迷宫问题求解

#构造迷宫
import numpy as np
map = [
    [0,1,0,0,0,0],
    [0,1,1,1,0,0],
    [0,1,0,1,1,0],
    [1,1,0,0,1,0],
    [0,0,0,0,0,0],
    [0,0,0,0,0,0]
]
start = [0,0]
end = [5,5]
print(map)
[[0, 1, 0, 0, 0, 0], [0, 1, 1, 1, 0, 0], [0, 1, 0, 1, 1, 0], [1, 1, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]
#定义一些都要用的函数
#方向数组,到时候加上这个数组就好
dist = [[0,1],[1,0],[0,-1],[-1,0]]
#标记以访问
def mark(map,pos):
    map[pos[0]][pos[1]] = 2
#判断能否走通
def ispossible(map, pos):
    return map[pos[0]][pos[1]] == 0

1.递归求解

#初始点,标记为搜索过, 如果已经是终点,结束,如果不是,找下一个点(上下左右四个方向搜索)
map = [
    [0,1,0,0,0,0],
    [0,1,1,1,0,0],
    [0,0,0,1,1,0],
    [1,1,0,0,1,0],
    [0,0,0,0,0,0],
    [0,0,0,0,0,0]
]
count = 0
def find_recurrence(map,pos):
    global count
    count += 1
    mark(map,pos)
    if pos == end:
        return True
    else:
        for i in range(0,4):
            next = [pos[0]+dist[i][0],pos[1]+dist[i][1]]
            if next[0] < 0 or next[1] < 0 or next[0] > 5 or next[1] > 5:
                continue
            if ispossible(map,next):
                if find_recurrence(map,next):
                    return True
    return False
if find_recurrence(map,start):
    print('找到,共用',count,'步')
    print(np.array(map).reshape(6,6))
else:
    print('没有找到')
找到,共用 11 步
[[2 1 0 0 0 0]
 [2 1 1 1 0 0]
 [2 2 2 1 1 0]
 [1 1 2 2 1 0]
 [0 0 0 2 2 2]
 [0 0 0 0 0 2]]

2.栈和回溯法

map = [
    [0,1,0,0,0,0],
    [0,1,1,1,0,0],
    [0,0,0,1,1,0],
    [1,1,0,0,1,0],
    [0,0,0,0,0,0],
    [0,0,0,0,0,0]
]
count = 0
stack = []
def find_recall(map,pos):
    global count,stack
    stack.append((pos,0)) #入栈的参数为位置以及搜索方向
    while len(stack)>0:
        pos, next = stack.pop()
        print(pos,next)
        for i in range(next, 4):
            nextp = [pos[0]+dist[i][0],pos[1]+dist[i][1]]
            if nextp[0] < 0 or nextp[1] < 0 or nextp[0] > 5 or nextp[1] > 5:
                continue
            if nextp == end:
                return True
            if ispossible(map,nextp):
                #原位置和下一个都进栈
                stack.append((pos,i+1))
                mark(map, nextp)
                stack.append((nextp,0))
                break
    return False
if find_recall(map,start):
    print('路径')
    print(stack)
    print(np.array(map).reshape(6,6))
else:
    print('没有找到')              
[0, 0] 0
[1, 0] 0
[2, 0] 0
[2, 1] 0
[2, 2] 0
[3, 2] 0
[3, 3] 0
[4, 3] 0
[4, 4] 0
[4, 5] 0
路径
[([0, 0], 2), ([1, 0], 2), ([2, 0], 1), ([2, 1], 1), ([2, 2], 2), ([3, 2], 1), ([3, 3], 2), ([4, 3], 1), ([4, 4], 1)]
[[0 1 0 0 0 0]
 [2 1 1 1 0 0]
 [2 2 2 1 1 0]
 [1 1 2 2 1 0]
 [0 0 0 2 2 2]
 [0 0 0 0 0 0]]

3.队列方法 略

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值