Python中DFS图的生成

2024-09-29 18:47:46 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,我试图对Python有一点精通,并决定制作一个迷宫是一件很有趣的事情。我找到了this page来说明一下如何做。在

   create a CellStack (LIFO) to hold a list of cell locations  
   set TotalCells = number of cells in grid  
   choose a cell at random and call it CurrentCell  
   set VisitedCells = 1  

    while VisitedCells < TotalCells 
        find all neighbors of CurrentCell with all walls intact   
        if one or more found 
            choose one at random  
            knock down the wall between it and CurrentCell  
            push CurrentCell location on the CellStack  
            make the new cell CurrentCell  
            add 1 to VisitedCells
        else 
            pop the most recent cell entry off the CellStack  
            make it CurrentCell
        endIf
    endWhile 

现在,我得到了下面的代码,尽管它并没有超过伪代码中显而易见的内容。在

^{pr2}$

我不确定这个类是做细胞的最好方法,但我还没有想到另一种方法。但是,我在检查一个小区的邻居时遇到了一些问题。find all neighbors of CurrentCell with all walls intact让我来做一个循环。在

你如何检查细胞是否是邻居?在


Tags: andofthetocellitrandomall
1条回答
网友
1楼 · 发布于 2024-09-29 18:47:46

你可以给每个单元格一个位置,存储为两个整数。那么,如果这些整数是邻居,那么两个细胞就是邻居。在

def isCellNeighbor(c1, c2):
   if abs(c1.x - c2.x) == 1: return True
   if abs(c1.y - c2.y) == 1: return True
   return False

上述方法将两个单元视为相邻单元,如果每个单元的至少一个角接触到另一个单元。你可以调整它以适应你的需要。在

PS:看看the amazing collection of maze algorithms

相关问题 更多 >

    热门问题