1. 程式人生 > >不相交類集演算法生成迷宮並求解路徑

不相交類集演算法生成迷宮並求解路徑

這兩天看了不相交類集演算法,十分高效於是寫了一個迷宮生成的演算法,事實證明該演算法效率極高;但求解路徑遇到了瓶頸,樓主這裡用鄰接表的方式尋找路徑,用棧儲存路徑資訊。該程式存在一個小問題:pain()函式閃爍的導致多次計算;而且路徑求解的演算法效率不高,本人菜鳥一枚,希望路過的大神予以指點。

public final class DisJoinSet {

    private int[] eleRoots;

    public DisJoinSet(int num){
        this.eleRoots = new int[num];
        for(int
i=0;i<num;i++){ getEleRoots()[i] = -1; } } public int find(int ele){ if(getEleRoots()[ele] < 0){ return ele; } return find(getEleRoots()[ele]); } public void union(int root1,int root2){ //讓深度較小的樹成為深度較大的樹的子樹 if
(getEleRoots()[root1] > getEleRoots()[root2]){ getEleRoots()[root1] = root2; }else{ if(getEleRoots()[root1] == getEleRoots()[root2]){//深度一樣,則更新深度 getEleRoots()[root1]--; } getEleRoots()[root2] = root1; } } public
int[] getEleRoots() { return eleRoots; } }
import javax.swing.*;
import java.awt.*;
import java.util.*;
import java.util.List;


/**
 * Created by 偉大的華仔 on 2017-11-30.
 */
public class Maze extends JFrame {

    private int row;//行數
    private int col;    //列數
    private DisJoinSet disjSet;
    private int winHeight=1000;//  行高
    private int winWidth=1000;//行寬


    public Maze(int row,int col){
        this.row = row;
        this.col = col;
        this.setTitle("迷宮");//設定標題
        this.setSize(winWidth,winHeight);//設定元件大小
        this.setVisible(true);//顯示或隱藏此 Window
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//設定使用者在此窗體上發起 "close" 時預設執行的操作  EXIT_ON_CLOSE(在 JFrame 中定義):使用 System exit 方法退出應用程式
    }

    public static void main(String[] args) {
        /**
         * 定義迷宮的大小,必須是正方形的
         * */
        int rowCount = 100;
        int colCount = 100;
        Maze maze = new Maze(rowCount,colCount);
    }
    @Override
    public void paint(Graphics g){
        super.paint(g);
        /**
         * 申請一個String集合,放置合併的節點
         * */
        List<Integer>DisList = new ArrayList<>();
        //背景為白色
        g.setColor(Color.white);
        g.fillRect(0, 0, winWidth, winHeight);//視窗填充矩形
        g.setColor(Color.black);
        final int extraWidth = 20;
        final int cellWidth = (winWidth-2*extraWidth)/row;//定義每個格子的寬度
        final int cellHeight = (winHeight-4*extraWidth)/col;//定義每個格子的高度
        for(int i=0;i<row;i++)  {
            for(int j=0;j<col;j++)
            {
                //初始化m*n矩陣格子
                g.drawRect(i*cellWidth+extraWidth,j*cellHeight+2*extraWidth, cellWidth, cellHeight);
            }
        }

        int lastPos = getLastElePos();//迷宮最後一個格式的代表數字
        //起點,終點特殊處理
        g.setColor(Color.red);
        g.fillRect(extraWidth, 2*extraWidth, cellWidth, cellHeight);
        g.fillRect((lastPos% row)*cellWidth + extraWidth,(lastPos/ row)*cellHeight + 2*extraWidth, cellWidth, cellHeight);

        this.setDisjSet(new DisJoinSet(row*col));
//      路徑記錄操作
        long start = System.currentTimeMillis();
        ArrayList<LinkedList<Integer>> adjoinTable = new ArrayList();
        LinkedList[] arrayFuck = new LinkedList[row*col];
        for (int i = 0;i<row*col;i++){
            LinkedList<Integer> temp = new LinkedList<Integer>();
            temp.add(i);
            arrayFuck[i] = temp;
            temp.clear();
        }
        Stack<Integer> pathSearch = new Stack<Integer>();
        pathSearch.push(0);
//        for (int i = 0;i<row*col;i++){
//            LinkedList<Integer> temp = new LinkedList<Integer>();
//            temp.add(i);
//            adjoinTable.add(temp);
//            temp.clear();
//        }
        long end1 = System.currentTimeMillis();
        System.out.println("構建資料消耗:"+(end1-start)+"ms");
        g.setColor(Color.white);  //用後景色擦色
        while(disjSet.find(0) != disjSet.find(lastPos)){//如果起點和終點還沒在同一個等價類
            /*
             *  在迷宮內隨機挖一個點,再找到該點周圍一點,使這兩個點落在同一個等價類
             */
            Random random = new Random();
            int randPos = random.nextInt(lastPos+1);//+1是為了能隨機到最後一位
            int rowIndex = randPos % row;
            int colIndex = randPos / col;
            List<Integer> neighborPos = getNeighborNums(rowIndex, colIndex) ;
            int randNeighbor = neighborPos.get(random.nextInt(neighborPos.size()));

            if(disjSet.find(randPos)  ==  disjSet.find(randNeighbor)){//兩點在同一個等價類
                continue;
            }else{
                int aRoot = disjSet.find(randPos);
                int bRoot = disjSet.find(randNeighbor);
                disjSet.union(aRoot, bRoot);
                DisList.add(randPos);
                DisList.add(randNeighbor);
//                /**
//                 * 列印搜尋過程
//                 * */
//                System.out.println("***過程分析*****************"+Arrays.toString(this.disjSet.getEleRoots()));
                int maxNum = Math.max(randPos, randNeighbor);//取得較大點
                int x1=0,y1=0,x2=0,y2=0;
                if(Math.abs(randPos-randNeighbor) == 1){//說明在同一行,用豎線隔開
                    x1= x2=(maxNum% row)*cellWidth + extraWidth;
                    y1=(maxNum/ row)*cellHeight + 2*extraWidth;
                    y2=y1+cellHeight;
                }else{//說明在同一列,用橫線隔開
                    y1=y2=(maxNum/ row)*cellHeight + 2*extraWidth;
                    x1=(maxNum% row)*cellWidth + extraWidth;
                    x2=x1+cellWidth;
                }
                g.drawLine(x1, y1, x2, y2);
            }
        }
        long end2 = System.currentTimeMillis();
        System.out.println("畫線和記錄資料資料消耗:"+(end2-end1)+"ms");
        /**
         * 列印陣列
         * */
//        System.out.println("***最終結構********************"+Arrays.toString(this.disjSet.getEleRoots()));
//        for (Iterator it = DisList.iterator();it.hasNext();){
//            System.out.println("***節點***"+it.next());
//        }
        for (int i = 0;i<DisList.size();i=i+2){
            Integer j = DisList.get(i);
            Integer k = DisList.get(i+1);
            arrayFuck[j].addLast(k);
            arrayFuck[k].addLast(j);
//            adjoinTable.get(j).addLast(k);
//            adjoinTable.get(k).addLast(j);
        }
//        for (int i = 0;i<adjoinTable.size();i++){
//            System.out.println("連結串列內容"+Arrays.toString(adjoinTable.get(i).toArray()));
//        }
        long end3 = System.currentTimeMillis();
        System.out.println("構建鄰接表消耗:"+(end3-end2)+"ms");
        /**
         * 演算法步驟
         * 1、檢索i節點的聯通節點
         * 2、存在就放入棧中(前提為棧中沒有該元素),不存在彈出棧頂元素(刪除鄰接表中的資料),或者為終點元素結束
         * 3、重複步驟1
         * */

        while (true){//while開始

//            System.out.println("******棧中內容:"+Arrays.toString(pathSearch.toArray()));
            if (pathSearch.isEmpty()){
                System.out.println("棧為空,迷宮沒有路徑");
                break;
            }

            if (pathSearch.peek()==(row*col-1)){
                System.out.println("迷宮已破解");
                break;
            }
//adjoinTable.get(pathSearch.peek()).size()==1 && pathSearch.peek() != 0
            if (arrayFuck[pathSearch.peek()].size() == 1 && pathSearch.peek() != 0){
                Integer temp = pathSearch.pop();
                if(pathSearch.isEmpty()){
                    System.out.println("棧為空,迷宮沒有路徑");
                    break;
                }else {
//                    adjoinTable.get(pathSearch.peek()).remove(temp);
//                    adjoinTable.get(temp).remove(pathSearch.peek());
                    arrayFuck[pathSearch.peek()].remove(temp);
                    arrayFuck[temp].remove(pathSearch.peek());
                }
            }else {
//                pathSearch.search(adjoinTable.get(pathSearch.peek()).get(0))!= -1
                if (pathSearch.search(arrayFuck[pathSearch.peek()].get(0))!= -1 ){
                    if (arrayFuck[pathSearch.peek()].size()>1){
//                        pathSearch.push(adjoinTable.get(pathSearch.peek()).get(1));
                        Iterator<Integer> boy = arrayFuck[pathSearch.peek()].listIterator();
                        while (boy.hasNext()){
                                int girl = boy.next();
                                if (!pathSearch.contains(girl)){
                                    pathSearch.push(girl);
                                }
                        }
                    }
                }else {
                    Integer arrayMenber = Integer.parseInt(arrayFuck[pathSearch.peek()].get(0).toString());
                    pathSearch.push(arrayMenber);
                }

            }

        }//while結束
        long end4 = System.currentTimeMillis();
        System.out.println("遍歷路徑表消耗:"+(end4-end3)+"ms");
        /**
         * 輸出路徑
         * */
//        System.out.println("迷宮路徑"+Arrays.toString(pathSearch.toArray()));
        g.setColor(Color.BLUE);
        while (!pathSearch.isEmpty()){
            int boy = pathSearch.pop();
            //左右
            g.fillOval((boy% row)*cellWidth + cellWidth/4+extraWidth,(boy/ row)*cellHeight + cellHeight/4+2*extraWidth, cellWidth/2, cellHeight/2);
        }
        long end5 = System.currentTimeMillis();
        System.out.println("畫路徑消耗:"+(end5-end4)+"ms");
        long end = System.currentTimeMillis();
        System.out.println("時間流程:"+Long.toString(end-start)+"ms");
        adjoinTable.clear();
        pathSearch.clear();
    }

    /**
     *  取得目標座標點周圍四個有效點
     */
    public List<Integer> getNeighborNums(int rowIndex,int colIndex){
        List<Integer> neighborPos = new ArrayList<Integer>(4);
        //右元素
        if(isPointInMaze(rowIndex+1,colIndex)){
            neighborPos.add(getCoordinateNum(rowIndex+1,colIndex));
        }
        //下元素
        if(isPointInMaze(rowIndex,colIndex+1)){
            neighborPos.add(getCoordinateNum(rowIndex,colIndex+1));
        }
        //左元素
        if(isPointInMaze(rowIndex-1,colIndex)){
            neighborPos.add(getCoordinateNum(rowIndex-1,colIndex));
        }
        //上元素
        if(isPointInMaze(rowIndex,colIndex-1)){
            neighborPos.add(getCoordinateNum(rowIndex,colIndex-1));
        }

        return neighborPos;
    }

    public int getLastElePos(){
        return row*col-1;
    }

    public DisJoinSet getDisjSet() {
        return disjSet;
    }

    public void setDisjSet(DisJoinSet disjSet) {
        this.disjSet = disjSet;
    }

    /**
     *  根據座標返回對應的值
     *  例如在4*3矩陣,(0,0)返回0;(3,2)返回10
     */
    public int getCoordinateNum(int x,int y){
        return y*col + x;
    }


    /**
     *  判斷給定座標是否在迷宮矩陣內
     */
    public boolean isPointInMaze(int x,int y){
        if(x < 0 || y < 0) return false;
        return x < row && y <col;
    }
}

這裡為100x100的結果展示,耗時最多5s。200x200的迷宮大致需要20s左右。

這裡寫圖片描述