1

I have a pathfinding project and I want to use Kruskal's algorithm as a maze generator. I am using a rank-based disjoint set data structure to detect cycles, which seems to be the standard way.

However, the mazes that I generate cannot be solved. Which leads me to think that there might be something wrong with my implementation logic.

init_walls() //m by n grid of walls
MST = {}

add each node to MST

while MST is not empty node = random_node() neighborNode = random_neighbor(node) //up, down, left or right

if find(node) not equal to find(neighborNode)
    convertWallToPassage(neighborNode)
    union(node, neighborNode)

delete node from MST

find and union are standard operations in the disjoint set used to detect cycles. If two nodes have the same parent, then they are in the same set and hence forms a cycle. I wonder if there is a gap in my logic, or is my approach flawed?

1 Answers1

1

Kruskal's algorithm iterates through edges, not through vertices. I think it would be better if it looked like:

init_walls() //m by n grid of walls

W = set of all walls p = 0 //counting the number of passages created

While p < m × n - 1 (u, v) = random_wall()

  if find(u) ≠ find(v)
       convertWallToPassage(u, v)
       union(u, v)
       p = p + 1

  delete (u, v) from walls

Here, $m\times n$ represents the number of nodes in an $m$ by $n$ grid. You could use the halting condition W is empty, but it is well known that a connected acyclic graph has one more node than edges.

Nathaniel
  • 18,309
  • 2
  • 30
  • 58