CS 61B homework9

注意分清楚vert和horiz就好。。。

part one

walls的表达方法我是用的 v or h/i/j,最后split一下就可以了,也可以构造一个wall,感觉好像会比较简单。

  public Maze(int horizontalSize, int verticalSize) {
    int i, j;

    horiz = horizontalSize;
    vert = verticalSize;
    if ((horiz < 1) || (vert < 1) || ((horiz == 1) && (vert == 1))) {
      return;                                    // There are no interior walls
    }

    // Create all of the horizontal interior walls.  Initially, every
    // horizontal wall exists; they will be removed later by the maze
    // generation algorithm.
    if (vert > 1) {
      hWalls = new boolean[horiz][vert - 1];
      for (j = 0; j < vert - 1; j++) {
        for (i = 0; i < horiz; i++) {
          hWalls[i][j] = true;
        }
      }
    }
    // Create all of the vertical interior walls.
    if (horiz > 1) {
      vWalls = new boolean[horiz - 1][vert];
      for (i = 0; i < horiz - 1; i++) {
        for (j = 0; j < vert; j++) {
          vWalls[i][j] = true;
        }
      }
    }



    /**
     * 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.
     **/

    int cellsnum = vert * horiz;
    int wallsnum = vert*(horiz-1) + horiz*(vert-1);
    DisjointSets cells = new DisjointSets(cellsnum);
    // array of walls
    String[] walls = new String[wallsnum];
    
    for (j = 0; j < vert - 1; j++) {
        for (i = 0; i < horiz; i++) {
            walls[j*horiz+i]="h"+"/"+i+"/"+j;
        }
      }
    for (i = 0; i < horiz - 1; i++) {
        for (j = 0; j < vert; j++) {
            walls[(vert-1)*horiz+i*vert+j]="v"+"/"+i+"/"+j;
        }
      }
    String temp;
    int randnum;
    for(int w = wallsnum;w>0;w--){
        randnum = randInt(w);
        temp = walls[w-1];
        walls[w-1] = walls[randnum];
        walls[randnum]=temp;
        
    }
    
    for(int num=0;num<wallsnum;num++){
        String[] d=walls[num].split("/");
        String VorH = d[0];
        i = Integer.parseInt(d[1]);
        j = Integer.parseInt(d[2]);

        if(VorH.equals("h")){
            if(cells.find(i*vert+j)!=cells.find(i*vert+j+1)){
                cells.union(cells.find(i*vert+j), cells.find(i*vert+j+1));
                hWalls[i][j] = false;
            }
        }else{
            if(cells.find(i*vert+j)!=cells.find((i+1)*vert+j)){
                cells.union(cells.find(i*vert+j), cells.find((i+1)*vert+j));
                vWalls[i][j] = false;
            }
        }
    }
  }
Maze

part two

原文地址:https://www.cnblogs.com/developerchen/p/7357758.html