Question: In Java Please Write a program that generates mazes of arbitrary size using the union-find algorithm . A simple algorithm to generate the maze is
In Java Please
Write a program that generates mazes of arbitrary size using the union-find algorithm. A simple algorithm to generate the maze is to start by creating an N x M grid of cells separated by walls on all sides, except for entrance and exit. Then continually choose a wall randomly, and knock it down if the cells are not already connected to each other. If we repeat the process until the starting and ending cells are connected, we have a maze. It is better to continue knocking down the walls until every cell is reachable from every cell as this would generate more false leads in the maze.
Test your algorithm by creating a 10 x 10 grid, and print all the walls that have been knocked down. Draw the resulting maze (hand-drawing is acceptable) and include the output of your program (see below).
- (If you don't include the output of your program, I won't be able to check that your drawing is correct, since your program will use random numbers.)
Solutions that do not use the union-find algorithm will receive 0 points. You can use the textbook code or implement union-find yourself, but I recommend using the textbook code. If you implement it yourself, any bugs in your implementation will affect your correctness grade.
Using thus union-find algorith!!
import java.util.Random;
import java.util.Scanner;
public class UF{
private int[] id;
private int count;
public UF(int N){
//initialize component id array.
count = N;
id = new int[N];
for(int i=0;i
id[i]=i;
}
public int count(){
return count;
}
public boolean connected(int p, int q){
return find(p) == find (q);
}
public find(int p)
public void union (int p, int q)
public static void main(Sting[] args){
int N = StdIn.readInt();
UF uf = new UF(N);
while(!stdIn.isEmpty()){
int p =StdIn.readInt();
int q =StdIn.readInt();
if (uf.connected(p , q)) continue;
uf.union(p ,q);
StdOut.println(p + " " + q);
}
StdOut.println(uf.count()+ " components");
}
}
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
