0

そこで、Pythonをもう少し習得しようとしています。迷路を作ることは、その方法を知るのに楽しいことだと思いました。私はそれを行う方法を少し説明しているこのページを見つけました。

   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 

今、私は次のコードを持っていますが、それは擬似コードの明白なものをはるかに超えていません。

class Cell:
    top_wall = 0
    bottom_wall = 0
    left_wall = 0
    right_wall = 0
    def knock_down(self,wall):
        if wall is 'top_wall' and self.top_wall is 0:
            self.top_wall = 1
        if wall is 'bottom_wall' and self.bottom_wall is 0:
            self.bottom_wall = 1
        if wall is 'left_wall' and self.left_wall is 0:
            self.left_wall = 1
        if wall is 'right_wall' and self.right_wall is 0:
            self.right_wall = 1
        else
            return 'Error: Wall Already Gone'

maze = [10][10]
CellStack = []          # LIFO stack to hold list of cell locations
TotalCells = 100        # Number of cells in grid
VisitedCells = 0        # Cells that have been visited
CurrentCell = 0         # The current cell

while VisitedCells < TotalCells:

クラスがセルを実行するための最良の方法であるかどうかはわかりませんが、私はまだそれを実行する別の方法を考えていません。ただし、セルの隣接セルをチェックする際に少し問題が発生しました。find all neighbors of CurrentCell with all walls intact少しループが発生します。

セルが隣接しているかどうかをどのように確認できますか?

4

1 に答える 1

1

各セルに位置を指定し、2 つの整数として格納できます。次に、それらの整数が隣接する場合、2 つのセルは隣接します。

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

上記は、少なくとも各セルの角が互いに接している場合、2 つのセルが隣接していると見なします。ニーズに合わせて微調整できます。

PS:迷路アルゴリズムのすばらしいコレクションをご覧ください

于 2012-07-07T20:06:45.963 に答える