Skip to content

Commit 897cd35

Browse files
committed
implement Kruskal's algorithm for creating random mazes with minimum spanning trees
1 parent 08b5b82 commit 897cd35

File tree

1 file changed

+47
-2
lines changed

1 file changed

+47
-2
lines changed

Assignment7/Trailblazer.cpp

+47-2
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@
99
#include "TrailblazerGraphics.h"
1010
#include "TrailblazerTypes.h"
1111
#include "TrailblazerPQueue.h"
12+
#include "pqueue.h"
13+
#include "random.h"
1214
using namespace std;
1315

1416
/* Function: shortestPath
@@ -88,6 +90,49 @@ shortestPath(Loc start, Loc end, Grid<double>& world,
8890
}
8991

9092
Set<Edge> createMaze(int numRows, int numCols) {
91-
// TODO: Fill this in!
92-
error("createMaze is not implemented yet.");
93+
Vector<Loc> nodes;
94+
Grid<bool> world(numRows, numCols);
95+
PriorityQueue<Edge> pq;
96+
Set<Edge> edges;
97+
Map< Loc, Set<Loc> > clusterMap;
98+
99+
/* Create Loc nodes */
100+
for (int col = 0; col < numCols; col++) {
101+
for (int row = 0; row < numRows; row++) {
102+
Loc node = makeLoc(row, col);
103+
Set<Loc> initSet;
104+
initSet.add(node);
105+
nodes.add(node);
106+
clusterMap.put(node, initSet);
107+
}
108+
}
109+
110+
/* Enqueue edges with random priority */
111+
for (int i = 0; i < nodes.size(); i++) {
112+
Vector<Loc> neighbors;
113+
neighbors.add(makeLoc(nodes[i].row, nodes[i].col - 1)); // left offset
114+
neighbors.add(makeLoc(nodes[i].row, nodes[i].col + 1)); // right offset
115+
neighbors.add(makeLoc(nodes[i].row - 1, nodes[i].col)); // up offset
116+
neighbors.add(makeLoc(nodes[i].row + 1, nodes[i].col)); // down offset
117+
foreach (Loc offset in neighbors) {
118+
if (world.inBounds(offset.row, offset.col)) {
119+
Edge e = makeEdge(nodes[i], offset);
120+
pq.enqueue(e, randomReal(0, 1));
121+
}
122+
}
123+
}
124+
125+
/* Create clusters */
126+
while (!pq.isEmpty()) {
127+
Edge path = pq.dequeue();
128+
if (clusterMap[path.start] != clusterMap[path.end]) {
129+
clusterMap[path.start] += clusterMap[path.end];
130+
clusterMap[path.end] += clusterMap[path.start];
131+
foreach (Loc node in clusterMap[path.start]) {
132+
clusterMap[node] += clusterMap[path.end];
133+
}
134+
edges.add(path);
135+
}
136+
}
137+
return edges;
93138
}

0 commit comments

Comments
 (0)