简体   繁体   中英

Randomized Prim's algorithm

I am writing a small project that allows you to generate random mazes using different algorithms and solve using different algorithms. I have already written depth-first search, A* search and recursive backtracker for some of the algorithms but I have tried to do prim

迷宫

As you can see it seems to generate a portion of the maze but not the rest. The different color lines are from when i resized the image, not sure why it did that.

I am following the pseudocode from the wikipedia page dedicated to maze generation algorithms ( https://en.wikipedia.org/wiki/Maze_generation_algorithm ) and I cannot see any error in my code. I will post the code if the problem cannot be resolved with some silly error that may be obvious.

def primsGeneration(Maze):
   nindex = [2, 3, 0, 1]
   startcell = [np.random.randint(0, Maze.size[0] - 1), np.random.randint(0, Maze.size[1] - 1)]
   Maze.visited[startcell[0]][startcell[1]] = 1
   walls = [[startcell[0], startcell[1], 0], [startcell[0], startcell[1], 1], [startcell[0], startcell[1], 2], [startcell[0], startcell[1], 3]]
   while len(walls) != 0:
       walls2add = []
       np.random.shuffle(walls)
       if walls[0][2] == 0: index = [walls[0][0], walls[0][1] - 1]
       elif walls[0][2] == 1: index = [walls[0][0] + 1, walls[0][1]]
       elif walls[0][2] == 2: index = [walls[0][0], walls[0][1] + 1]
       else: index = [walls[0][0] - 1, walls[0][1]]
       if Maze.validatecurrentpos(index):
           if int(Maze.visited[walls[0][0]][walls[0][1]]) ^ int(Maze.visited[index[0]][index[1]]):
                Maze.wallarray[walls[0][0]][walls[0][1]][walls[0][2]] = 0
                Maze.wallarray[index[0]][index[1]][nindex[walls[0][2]]] = 0
                Maze.visited[index[0]][index[1]] = 1
                w2a = Maze.wallarray[index[0]][index[1]]
                for wall in w2a:
                    walls2add.append([index[0], index[1], wall])
                for wall in walls2add:
                    walls.append(wall)
        walls.pop(0)

I am using a Maze object that I have written but simply, wallarray is a numpy array of all walls in the maze, format [x][y][direction]. If it is 1 the wall is there, directions are (0 UP, 1 RIGHT, 2 DOWN, 3 LEFT). Visited is simply a array of 0's, 1 means it has been visited.

Ok I have found the solution. It was indeed a silly mistake, where I wasnt getting the correct walls from the Maze object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM