社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

python中的迷宫生成器

Samy • 4 年前 • 1312 次点击  

我尝试使用回溯在python中编写一个完美的(只有一个解决方案)迷宫生成器。

首先,我的迷宫用x*y网格表示

enter image description here

每一行代表一堵墙。 我的程序将从左上角的单元格(标记为1)开始,并检查任何可能的移动(2或6),然后它将在这两个单元格之间随机选择,并将单元格标签添加到堆栈中,我们重复相同的过程,直到堆栈满为止(在本例中,25个项目),当我们到达死端时,程序应通过从堆栈中弹出项目并采取另一条路径,可以进行回溯。

为了更好的解释,你可以参考这个 website

我的代码是:

import random

dim_x = 5
dim_y = 5

grid = [[0 for i in range(dim_x)] for j in range(dim_y)]
visited = [1]

def valid(nb):
    if nb >= 1 and nb <= dim_x * dim_y:
        return True
    return False

def list_moves(nb):
    moves = []
    nb = int(nb)
    if valid(nb + dim_y) and visited.count(nb + dim_y) < 1:
        moves.append(nb + dim_y)
    if valid(nb - dim_y) and visited.count(nb - dim_y) < 1:
        moves.append(nb - dim_y)
    if valid(nb + 1) and visited.count(nb + 1) < 1 and nb % dim_x != 0:
        moves.append(nb + 1)
    if valid(nb - 1) and visited.count(nb - 1) < 1 and nb % dim_x != 1:
        moves.append(nb - 1)
    return moves

def gen():
    while len(list_moves(visited[len(visited) - 1])) < 1:
        visited.pop()
    next_visit = random.choice(list_moves(visited[len(visited) - 1]))
    visited.append(next_visit)

while len(visited) != dim_x * dim_y:
    gen()
    print(visited)

当尝试创建5x5迷宫时,我主要被困在23个单元格中,例如,我的堆栈如下:1、2、7、6、11、12、13、8、9、4、5、10、15、14、19、20、25、24、23、22、21、16、17

我知道错误来自gen()函数。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/38738
 
1312 次点击  
文章 [ 2 ]  |  最新文章 4 年前
Ajay Srivastava
Reply   •   1 楼
Ajay Srivastava    5 年前

保留两个变量,一个用于遍历路径,另一个用于访问的节点,可以解决这个问题。另外,由于遍历应该是这个程序的输出,所以不应该从遍历路径中弹出任何内容。

def gen():
    pathLen = len(path)
    nextNode = path[pathLen - 1]
    while len(list_moves(nextNode)) < 1:
        pathLen -= 1
        nextNode = path[pathLen-1]
        path.append(nextNode)

    next_visit = random.choice(list_moves(path[len(path) - 1]))
    visited.append(next_visit)
    path.append(next_visit)
blhsing
Reply   •   2 楼
blhsing    5 年前

通过弹出 visited 当你后退时,你会破坏你的道路。您应该使用索引来跟踪您的回溯:

def gen():
    pos = len(visited) - 1
    while len(list_moves(visited[pos])) < 1:
        pos -= 1
    next_visit = random.choice(list_moves(visited[pos]))
    visited.append(next_visit)

有了这个变化,一个 访问 将是:

[1, 2, 7, 12, 11, 16, 17, 18, 23, 24, 25, 20, 19, 14, 15, 10, 5, 4, 9, 8, 13, 3, 22, 21, 6]