1. 程式人生 > >java深度優先、非遞迴深度優先、廣度優先迷宮求解視覺化

java深度優先、非遞迴深度優先、廣度優先迷宮求解視覺化

本文將從以下幾個維度來求解迷宮最終路徑

1、深度優先遞迴求解最終路徑
2、非遞迴深度優先走迷宮求解最終路徑
3、廣度優先走迷宮求解最終路徑

通用工具類

import java.awt.*;
import java.awt.geom.Ellipse2D;

import java.awt.geom.Rectangle2D;
import java.lang.InterruptedException;


public class AlgoVisHelper {

    private AlgoVisHelper(){}

    public static final Color Red = new
Color(0xF44336); public static final Color Pink = new Color(0xE91E63); public static final Color Purple = new Color(0x9C27B0); public static final Color DeepPurple = new Color(0x673AB7); public static final Color Indigo = new Color(0x3F51B5); public static final Color Blue = new Color(0x2196F3
); public static final Color LightBlue = new Color(0x03A9F4); public static final Color Cyan = new Color(0x00BCD4); public static final Color Teal = new Color(0x009688); public static final Color Green = new Color(0x4CAF50); public static final Color LightGreen = new Color(0x8BC34A); public
static final Color Lime = new Color(0xCDDC39); public static final Color Yellow = new Color(0xFFEB3B); public static final Color Amber = new Color(0xFFC107); public static final Color Orange = new Color(0xFF9800); public static final Color DeepOrange = new Color(0xFF5722); public static final Color Brown = new Color(0x795548); public static final Color Grey = new Color(0x9E9E9E); public static final Color BlueGrey = new Color(0x607D8B); public static final Color Black = new Color(0x000000); public static final Color White = new Color(0xFFFFFF); public static void strokeCircle(Graphics2D g, int x, int y, int r){ Ellipse2D circle = new Ellipse2D.Double(x-r, y-r, 2*r, 2*r); g.draw(circle); } public static void fillCircle(Graphics2D g, int x, int y, int r){ Ellipse2D circle = new Ellipse2D.Double(x-r, y-r, 2*r, 2*r); g.fill(circle); } public static void strokeRectangle(Graphics2D g, int x, int y, int w, int h){ Rectangle2D rectangle = new Rectangle2D.Double(x, y, w, h); g.draw(rectangle); } public static void fillRectangle(Graphics2D g, int x, int y, int w, int h){ Rectangle2D rectangle = new Rectangle2D.Double(x, y, w, h); g.fill(rectangle); } public static void setColor(Graphics2D g, Color color){ g.setColor(color); } public static void setStrokeWidth(Graphics2D g, int w){ int strokeWidth = w; g.setStroke(new BasicStroke(strokeWidth, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND)); } public static void pause(int t) { try { Thread.sleep(t); } catch (InterruptedException e) { System.out.println("Error sleeping"); } } }

深度優先遞迴求解最終路徑

資料層

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Scanner;


public class MazeData {

    public static final char ROAD = ' ';
    public static final char WALL = '#';

    private int entranceX, entranceY;
    private int exitX, exitY;

    private int N, M;
    private char[][] maze;                      // 儲存資料
    public boolean[][] path;                    // 是否為正確路徑
    public boolean[][] visited;                 // 是否訪問過

    public MazeData(String filename){

        if(filename == null)
            throw new IllegalArgumentException("Filename can not be null!");

        Scanner scanner = null;
        try{
            File file = new File(filename);
            if(!file.exists())
                throw new IllegalArgumentException("File " + filename + " doesn't exist");

            FileInputStream fis = new FileInputStream(file);
            scanner = new Scanner(new BufferedInputStream(fis), "UTF-8");

            // 讀取第一行
            String nmline = scanner.nextLine();
            String[] nm = nmline.trim().split("\\s+");
            //System.out.print(nm[0] + ' ' + nm[1]);

            N = Integer.parseInt(nm[0]);
            // System.out.println("N = " + N);
            M = Integer.parseInt(nm[1]);
            // System.out.println("M = " + M);

            // 讀取後續的N行
            visited = new boolean[N][M];
            path = new boolean[N][M];
            maze = new char[N][M];
            for(int i = 0 ; i < N ; i ++){
                String line = scanner.nextLine();

                // 每行保證有M個字元
                if(line.length() != M)
                    throw new IllegalArgumentException("Maze file " + filename + " is invalid");
                for(int j = 0 ; j < M ; j ++)
                    maze[i][j] = line.charAt(j);
            }
        }
        catch(IOException e){
            e.printStackTrace();
        }
        finally {
            if(scanner != null)
                scanner.close();
        }

        entranceX = 1;
        entranceY = 0;
        exitX = N - 2;
        exitY = M - 1;
    }

    public int N(){ return N; }
    public int M(){ return M; }
    public int getEntranceX(){return entranceX;}
    public int getEntranceY(){return entranceY;}
    public int getExitX(){return exitX;}
    public int getExitY(){return exitY;}
    public char getMaze(int i, int j){
        if(!inArea(i,j))
            throw new IllegalArgumentException("i or j is out of index in getMaze!");
        return maze[i][j];
    }

    public boolean inArea(int x, int y){
        return x >= 0 && x < N && y >= 0 && y < M;
    }
    // 列印迷宮文字資訊
    public void print(){
        System.out.println(N + " " + M);
        for(int i = 0 ; i < N ; i ++){
            for(int j = 0 ; j < M ; j ++)
                System.out.print(maze[i][j]);
            System.out.println();
        }
        return;
    }

}

檢視層

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class AlgoFrame extends JFrame{

    private int canvasWidth;
    private int canvasHeight;

    public AlgoFrame(String title, int canvasWidth, int canvasHeight){

        super(title);

        this.canvasWidth = canvasWidth;
        this.canvasHeight = canvasHeight;

        AlgoCanvas canvas = new AlgoCanvas();
        setContentPane(canvas);
        pack();

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setResizable(false);

        setVisible(true);
    }

    public AlgoFrame(String title){

        this(title, 1024, 768);
    }

    public int getCanvasWidth(){return canvasWidth;}
    public int getCanvasHeight(){return canvasHeight;}

    // data
    private MazeData data;
    public void render(MazeData data){
        this.data = data;
        repaint();
    }

    private class AlgoCanvas extends JPanel{

        public AlgoCanvas(){
            // 雙快取
            super(true);
        }

        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);

            Graphics2D g2d = (Graphics2D)g;

            // 抗鋸齒
//            RenderingHints hints = new RenderingHints(
//                    RenderingHints.KEY_ANTIALIASING,
//                    RenderingHints.VALUE_ANTIALIAS_ON);
//            hints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
//            g2d.addRenderingHints(hints);

            // 具體繪製
            int w = canvasWidth/data.M();
            int h = canvasHeight/data.N();

            for(int i = 0 ; i < data.N() ; i ++ )
                for(int j = 0 ; j < data.M() ; j ++){
                    // 判斷是否是牆
                    if (data.getMaze(i,j) == MazeData.WALL)
                        AlgoVisHelper.setColor(g2d, AlgoVisHelper.LightBlue);
                    else
                        AlgoVisHelper.setColor(g2d, AlgoVisHelper.White);
                    // 判斷是否是正確路線
                    if(data.path[i][j])
                        AlgoVisHelper.setColor(g2d, AlgoVisHelper.Yellow);

                    AlgoVisHelper.fillRectangle(g2d, j * w, i * h, w, h);
                }
        }

        @Override
        public Dimension getPreferredSize(){
            return new Dimension(canvasWidth, canvasHeight);
        }
    }
}

控制層

import java.awt.EventQueue;

public class AlgoVisualizer {

    private static int DELAY = 5;               // 等待時間
    private static int blockSide = 8;           // 繪製正方形大小

    private MazeData data;
    private AlgoFrame frame;
    // 座標偏移方向
    private static final int d[][] = {{-1,0},{0,1},{1,0},{0,-1}};

    public AlgoVisualizer(String mazeFile){

        // 初始化資料
        data = new MazeData(mazeFile);
        // 需繪製的迷宮長度寬度乘以需要繪製的大小得出畫布高度寬度
        int sceneHeight = data.N() * blockSide;
        int sceneWidth = data.M() * blockSide;

        // 初始化檢視
        EventQueue.invokeLater(() -> {
            frame = new AlgoFrame("Maze Solver Visualization", sceneWidth, sceneHeight);

            new Thread(() -> {
                run();
            }).start();
        });
    }

    public void run(){

        setData(-1, -1, false);
        // 如果該迷宮無解,給出提示
        if(!go(data.getEntranceX(), data.getEntranceY()))
            System.out.println("The maze has NO solution!");

        setData(-1, -1, false);
    }

    // 從(x,y)的位置開始求解迷宮,如果求解成功,返回true;否則返回false
    private boolean go(int x, int y){
        // 是否處於迷宮內
        if(!data.inArea(x,y))
            throw new IllegalArgumentException("x,y are out of index in go function!");
        // 將處理過的座標記錄
        data.visited[x][y] = true;
        setData(x, y, true);
        // 如果到達出口返回true
        if(x == data.getExitX() && y == data.getExitY())
            return true;
        // 遍歷四個方向,如果是正確路線返回true,進行繪製
        for(int i = 0 ; i < 4 ; i ++){
            int newX = x + d[i][0];
            int newY = y + d[i][1];
            if(data.inArea(newX, newY) &&
                    data.getMaze(newX,newY) == MazeData.ROAD &&
                    !data.visited[newX][newY])
                if(go(newX, newY))
                    return true;
        }

        // 回溯,該座標不為正確路線,將路線標識置為false
        setData(x, y, false);

        return false;
    }

    private void setData(int x, int y, boolean isPath){
        if(data.inArea(x, y))
            data.path[x][y] = isPath;

        frame.render(data);
        AlgoVisHelper.pause(DELAY);
    }

    public static void main(String[] args) {

        String mazeFile = "D:\\gz\\workspace11\\text\\src\\maze_101_101.txt";

        AlgoVisualizer vis = new AlgoVisualizer(mazeFile);
    }
}

執行效果圖

這裡寫圖片描述

非遞迴深度優先走迷宮求解最終路徑

資料層

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Scanner;


public class MazeData {

    public static final char ROAD = ' ';
    public static final char WALL = '#';

    private int entranceX, entranceY;
    private int exitX, exitY;

    private int N, M;
    private char[][] maze;
    public boolean[][] path;
    public boolean[][] visited;
    public boolean[][] result;

    public MazeData(String filename){

        if(filename == null)
            throw new IllegalArgumentException("Filename can not be null!");

        Scanner scanner = null;
        try{
            File file = new File(filename);
            if(!file.exists())
                throw new IllegalArgumentException("File " + filename + " doesn't exist");

            FileInputStream fis = new FileInputStream(file);
            scanner = new Scanner(new BufferedInputStream(fis), "UTF-8");

            // 讀取第一行
            String nmline = scanner.nextLine();
            String[] nm = nmline.trim().split("\\s+");
            //System.out.print(nm[0] + ' ' + nm[1]);

            N = Integer.parseInt(nm[0]);
            // System.out.println("N = " + N);
            M = Integer.parseInt(nm[1]);
            // System.out.println("M = " + M);

            // 讀取後續的N行
            visited = new boolean[N][M];
            path = new boolean[N][M];
            result = new boolean[N][M];
            maze = new char[N][M];
            for(int i = 0 ; i < N ; i ++){
                String line = scanner.nextLine();

                // 每行保證有M個字元
                if(line.length() != M)
                    throw new IllegalArgumentException("Maze file " + filename + " is invalid");
                for(int j = 0 ; j < M ; j ++){
                    maze[i][j] = line.charAt(j);
                    visited[i][j] = false;
                    path[i][j] = false;
                    result[i][j] = false;
                }
            }
        }
        catch(IOException e){
            e.printStackTrace();
        }
        finally {
            if(scanner != null)
                scanner.close();
        }

        entranceX = 1;
        entranceY = 0;
        exitX = N - 2;
        exitY = M - 1;
    }

    public int N(){ return N; }
    public int M(){ return M; }
    public int getEntranceX(){return entranceX;}
    public int getEntranceY(){return entranceY;}
    public int getExitX(){return exitX;}
    public int getExitY(){return exitY;}
    public char getMaze(int i, int j){
        if(!inArea(i,j))
            throw new IllegalArgumentException("i or j is out of index in getMaze!");
        return maze[i][j];
    }

    public boolean inArea(int x, int y){
        return x >= 0 && x < N && y >= 0 && y < M;
    }

    public void print(){
        System.out.println(N + " " + M);
        for(int i = 0 ; i < N ; i ++){
            for(int j = 0 ; j < M ; j ++)
                System.out.print(maze[i][j]);
            System.out.println();
        }
        return;
    }

}
public class Position {

    private int x, y;
    private Position prev;

    public Position(int x, int y, Position prev){
        this.x = x;
        this.y = y;
        this.prev = prev;
    }

    public Position(int x, int y){
        this(x, y, null);
    }

    public int getX(){return x;}
    public int getY(){return y;}
    public Position getPrev(){return prev;}
}

檢視層

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class AlgoFrame extends JFrame{

    private int canvasWidth;
    private int canvasHeight;

    public AlgoFrame(String title, int canvasWidth, int canvasHeight){

        super(title);

        this.canvasWidth = canvasWidth;
        this.canvasHeight = canvasHeight;

        AlgoCanvas canvas = new AlgoCanvas();
        setContentPane(canvas);
        pack();

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setResizable(false);

        setVisible(true);
    }

    public AlgoFrame(String title){

        this(title, 1024, 768);
    }

    public int getCanvasWidth(){return canvasWidth;}
    public int getCanvasHeight(){return canvasHeight;}

    // data
    private MazeData data;
    public void render(MazeData data){
        this.data = data;
        repaint();
    }

    private class AlgoCanvas extends JPanel{

        public AlgoCanvas(){
            // 雙快取
            super(true);
        }

        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);

            Graphics2D g2d = (Graphics2D)g;

            // 抗鋸齒
//            RenderingHints hints = new RenderingHints(
//                    RenderingHints.KEY_ANTIALIASING,
//                    RenderingHints.VALUE_ANTIALIAS_ON);
//            hints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
//            g2d.addRenderingHints(hints);

            // 具體繪製
            int w = canvasWidth/data.M();
            int h = canvasHeight/data.N();

            for(int i = 0 ; i < data.N() ; i ++ )
                for(int j = 0 ; j < data.M() ; j ++){
                    // 判斷是否為牆
                    if (data.getMaze(i,j) == MazeData.WALL)
                        AlgoVisHelper.setColor(g2d, AlgoVisHelper.LightBlue);
                    else
                        AlgoVisHelper.setColor(g2d, AlgoVisHelper.White);
                    // 判斷是否為以處理
                    if(data.path[i][j])
                        AlgoVisHelper.setColor(g2d, AlgoVisHelper.Yellow);
                    // 判斷是否為正確路徑
                    if(data.result[i][j])
                        AlgoVisHelper.setColor(g2d, AlgoVisHelper.Red);

                    AlgoVisHelper.fillRectangle(g2d, j * w, i * h, w, h);
                }
        }

        @Override
        public Dimension getPreferredSize(){
            return new Dimension(canvasWidth, canvasHeight);
        }
    }
}

控制層

import java.awt.*;
import java.util.Stack;

public class AlgoVisualizer {

    private static int DELAY = 5;
    private static int blockSide = 8;

    private MazeData data;
    private AlgoFrame frame;
    private static final int d[][] = {{-1,0},{0,1},{1,0},{0,-1}};

    public AlgoVisualizer(String mazeFile){

        // 初始化資料
        data = new MazeData(mazeFile);
        int sceneHeight = data.N() * blockSide;
        int sceneWidth = data.M() * blockSide;

        // 初始化檢視
        EventQueue.invokeLater(() -> {
            frame = new AlgoFrame("Maze Solver Visualization", sceneWidth, sceneHeight);

            new Thread(() -> {
                run();
            }).start();
        });
    }

    private void run(){
        // 初始繪製
        setData(-1, -1, false);

        Stack<Position> stack = new Stack<Position>();
        Position entrance = new Position(data.getEntranceX(), data.getEntranceY());
        // 壓入起始座標
        stack.push(entrance);
        // 設定成以處理
        data.visited[entrance.getX()][entrance.getY()] = true;

        boolean isSolved = false;

        while(!stack.empty()){
            Position curPos = stack.pop();
            setData(curPos.getX(), curPos.getY(), true);
            // 如果為出口返回真,並回溯正確路徑,改變其繪製顏色
            if(curPos.getX() == data.getExitX() && curPos.getY() == data.getExitY()){
                isSolved = true;
                findPath(curPos);
                break;
            }

            for(int i = 0 ; i < 4  ; i ++){
                int newX = curPos.getX() + d[i][0];
                int newY = curPos.getY() + d[i][1];
                // 如果座標點在迷宮內、並且沒有處理、並且等於可以前進的路線則壓入,並將其設為以處理
                if(data.inArea(newX, newY)
                        && !data.visited[newX][newY]
                        && data.getMaze(newX, newY) == MazeData.ROAD){
                    stack.push(new Position(newX, newY, curPos));
                    data.visited[newX][newY] = true;
                }
            }

        }

        if(!isSolved)
            System.out.println("The maze has no Solution!");

        setData(-1, -1, false);
    }

    private void findPath(Position des){

        Position cur = des;
        // 依次呼叫上一路徑座標,改變其繪製顏色
        while(cur != null){
            data.result[cur.getX()][cur.getY()] = true;
            cur = cur.getPrev();
        }
    }

    private void setData(int x, int y, boolean isPath){
        if(data.inArea(x, y))
            data.path[x][y] = isPath;

        frame.render(data);
        AlgoVisHelper.pause(DELAY);
    }

    public static void main(String[] args) {

        String mazeFile = "D:\\gz\\workspace11\\text\\src\\maze_101_101.txt";

        AlgoVisualizer vis = new AlgoVisualizer(mazeFile);
    }
}

執行效果圖

這裡寫圖片描述

廣度優先走迷宮求解最終路徑

控制層(其餘沿用非遞迴深度優先)

import java.awt.EventQueue;
import java.util.LinkedList;

public class AlgoVisualizer {

    private static int DELAY = 5;
    private static int blockSide = 8;

    private MazeData data;
    private AlgoFrame frame;
    private static final int d[][] = {{-1,0},{0,1},{1,0},{0,-1}};

    public AlgoVisualizer(String mazeFile){

        // 初始化資料
        data = new MazeData(mazeFile);
        int sceneHeight = data.N() * blockSide;
        int sceneWidth = data.M() * blockSide;

        // 初始化檢視
        EventQueue.invokeLater(() -> {
            frame = new AlgoFrame("Maze Solver Visualization", sceneWidth, sceneHeight);

            new Thread(() -> {
                run();
            }).start();
        });
    }

    private void run(){

        setData(-1, -1, false);
        LinkedList<Position> queue = new LinkedList<Position>();
        Position entrance = new Position(data.getEntranceX(), data.getEntranceY());
        // 入口新增到隊尾
        queue.addLast(entrance);
        // 設定以處理
        data.visited[entrance.getX()][entrance.getY()] = true;

        boolean isSolved = false;

        while(queue.size() != 0){
            // 取佇列頭部元素
            Position curPos = queue.pop();
            setData(curPos.getX(), curPos.getY(), true);
            // 如果是出口返回真,並回溯真實路徑,改變其繪製顏色
            if(curPos.getX() == data.getExitX() && curPos.getY() == data.getExitY()){
                isSolved = true;
                // 回溯真實路徑
                findPath(curPos);
                break;
            }

            for(int i = 0 ; i < 4  ; i ++){
                int newX = curPos.getX() + d[i][0];
                int newY = curPos.getY() + d[i][1];
                // 如果座標點在迷宮內、並且沒有處理、並且等於可以前進的路線則壓入,並將其設為以處理
                if(data.inArea(newX, newY)
                        && !data.visited[newX][newY]
                        && data.getMaze(newX, newY) == MazeData.ROAD){
                    // 壓入隊尾
                    queue.addLast(new Position(newX, newY, curPos));
                    // 設定為以處理
                    data.visited[newX][newY] = true;
                }
            }

        }

        if(!isSolved)
            System.out.println("The maze has no Solution!");

        setData(-1, -1, false);
    }

    private void findPath(Position des){

        Position cur = des;
        while(cur != null){
            data.result[cur.getX()][cur.getY()] = true;
            cur = cur.getPrev();
        }
    }

    private void setData(int x, int y, boolean isPath){
        if(data.inArea(x, y))
            data.path[x][y] = isPath;

        frame.render(data);
        AlgoVisHelper.pause(DELAY);
    }

    public static void main(String[] args) {

        String mazeFile = "D:\\gz\\workspace11\\text\\src\\maze_101_101.txt";

        AlgoVisualizer vis = new AlgoVisualizer(mazeFile);
    }
}

執行效果圖

這裡寫圖片描述

總結

如果迷宮有多個解,那麼深度優先求得的是第一個解,而廣度優先則求得的是最短的解

這裡寫圖片描述