python迷宫问题模拟程序,Python中迷宫求解程序性能的改进

各位程序员。我的一个项目需要帮助。我在做一个解决迷宫的程序。它读取一个图像文件,它必须是黑白的(黑色像素是墙,白色像素是路径),顶部只有一个像素是迷宫的入口,底部只有一个白色像素是出口。在

代码有三个主要部分:

1)程序首先在迷宫中创建节点,遵循一组规则。例如,这里有一个简单的迷宫:

74e1791ce0c049db081ec7c47de181e1.gif

所有节点都用红色绘制:

1ca22a4b26fddab23596125a856a8c2f.png

节点就像角落,十字路口,每个可以改变方向的点。还测量了每个节点到迷宫出口的距离。当它生成所有节点时,它将它们放在一个列表中。在

2)一旦生成所有节点,程序将遍历列表中的所有节点,并尝试在每个可能的方向搜索其他节点,以“链接”它们,建立可能的路径。例如,如果它检测到某个节点上方有一条路径,它将从该节点的坐标开始搜索一行中的每一个像素,然后再向上遍历所有节点列表,以查看另一个节点是否与这些坐标匹配。如果它在某个点找到一个,它会将它们链接起来,然后开始向右搜索(当然,如果有一条通向右侧的路径),等等,搜索每个方向。在

3)一旦所有的节点连接在一起,每个可能的路径都建立起来了,它将从迷宫的入口节点开始,运行我的A*算法实现来找出正确的路径,如果它走到了死胡同,它就会返回。如你所见,它解决迷宫没有困难。在

ecf29ef2259487faeb3f23c491f31047.png

所以我的程序起作用了。那有什么问题吗?

问题是节点连接部分。在小迷宫上,大约需要半秒钟。但是如果迷宫稍微大一点,那么节点的数量就会急剧增加。如果每个节点有600个节点,我可以想象它每迭代一次。。。这需要很长时间。在

所以这就是我请求帮助的原因:一种更好、更快的方式将节点连接在一起。

我已经在pastebin(https://pastebin.com/xtmTm7wb)上发布了整个代码,如果有点乱,很抱歉,当我编程时已经很晚了。节点连接部分从第133行开始,到第196行结束。在

以下是节点链接代码:counter = 0

last = 0

for node in nodelist:

a = node.pos[0]

b = node.pos[1]

if node.paths[0]:

for i in range(b-1,0,-1):

if mazepix[a,i] == blackpix:

break

if any(x.pos == (a,i) for x in nodelist):

for iteration in nodelist:

if iteration.pos == (a,i):

indexofnodetolinkto = iteration.index

break

node.connections.append(indexofnodetolinkto)

# print("Linking node %d and node %d..."%(node.index, indexofnodetolinkto))

break

if node.paths[1]:

for i in range(a+1,maze.size[0]):

if mazepix[i,b] == blackpix:

break

if any(x.pos == (i,b) for x in nodelist):

for iteration in nodelist:

if iteration.pos == (i,b):

indexofnodetolinkto = iteration.index

break

node.connections.append(indexofnodetolinkto)

# print("Linking node %d and node %d..."%(node.index, indexofnodetolinkto))

break

if node.paths[2]:

for i in range(b+1,maze.size[1]):

if mazepix[a,i] == blackpix:

break

if any(x.pos == (a,i) for x in nodelist):

for iteration in nodelist:

if iteration.pos == (a,i):

indexofnodetolinkto = iteration.index

break

node.connections.append(indexofnodetolinkto)

# print("Linking node %d and node %d..."%(node.index, indexofnodetolinkto))

break

if node.paths[3]:

for i in range(a-1,0,-1):

if mazepix[i,b] == blackpix:

break

if any(x.pos == (i,b) for x in nodelist):

for iteration in nodelist:

if iteration.pos == (i,b):

indexofnodetolinkto = iteration.index

break

node.connections.append(indexofnodetolinkto)

# print("Linking node %d and node %d..."%(node.index, indexofnodetolinkto))

break

counter += 1

percent = (counter/nbrofnodes)*100

if int(percent)%10 == 0 and int(percent) != last:

print("Linking %d%% done..."%percent)

last = int(percent)

print("All node linked.")

谢谢你,如果你读了所有这些,我知道这不是一个非常精确的问题,但我花了太多的时间试图使这个工作,现在,我真的被困在我可以改进它的方法上。在

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值