本次作业主要学会运用Disjoin Sets,DisjointSets的class作业已经写好给出。class中两个重要的方法是find和union,find(x)方法返回x的root,并在搜寻过程中递归使用path compression,使得路径上的每个node直接指向root。Union(root1,root2)方法将两个set的root指向其中等级高的那个,else使root1成为新的root。
在Maze.class中,要先创建walls[],然后使这些wall的排序处于一个随机的状态。可以将前一半的wall设置成有序,后一半的wall设置成无序的负数,然后用题目提示的交换首尾的方法使整个wall[]变成random。最后通过cell的union把不同set结合在一起,将hWalls[]或vWalls[]的boolean值设置为false,remove the walls.
The end.
以下为题目中需要fill out 的代码:
/** * Fill in the rest of this method. You should go through all the walls of * the maze in random order, and remove any wall whose removal will not * create a cycle. Use the implementation of disjoint sets provided in the * set package to avoid creating any cycles. * * Note the method randInt() further below, which generates a random * integer. randInt() generates different numbers every time the program * is run, so that you can make lots of different mazes. **/ DisjointSets cell = new DisjointSets(horiz * vert); int numOfHWalls = horiz * (vert - 1); int numOfVWalls = (horiz - 1) * vert; int numOfWalls = numOfHWalls + numOfVWalls; int[] Walls = new int[numOfWalls]; int index = 0; if (vert > 1){ for (j = 0; j < vert - 1; j++){ for (i = 0; i < horiz; i++){ Walls[index] = j * horiz + i; index++; } } } if (horiz > 1){ for (i = 0; i < horiz - 1; i++){ for (j = 0; j < vert; j++){ Walls[index] = -(j * horiz + i); index++; } } } //Order the interior walls of the maze in a random order int w = numOfWalls; while (w > 1){ int x = randInt(w); int temp = Walls[x]; Walls[x] = Walls[w-1]; Walls[w-1] = temp; w--; } //Remove interior walls for (int k = 0; k < numOfWalls; k++){ index = Walls[k]; if (index > 0){ int cell1 = cell.find(index); int cell2 = cell.find(index + horiz); if (cell1 != cell2){ cell.union(cell1,cell2); hWalls[index % horiz][index/horiz] = false; } }else { int cell1 = cell.find(-index); int cell2 = cell.find(-index + 1); if (cell1 != cell2){ cell.union(cell1,cell2); vWalls[(-index)%horiz][(-index)/horiz] = false; } } }