最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java分別利用深度優(yōu)先和廣度優(yōu)先求解迷宮路徑

 更新時(shí)間:2022年08月29日 10:06:03   作者:天人合一peng  
這篇文章主要為大家詳細(xì)介紹了Java如何利用深度優(yōu)先的非遞歸遍歷方法和廣度優(yōu)先的遍歷方法實(shí)現(xiàn)求解迷宮路徑,文中的示例代碼講解詳細(xì),需要的可以參考一下

深度優(yōu)先

實(shí)現(xiàn)效果

示例代碼

import java.awt.*;
import javax.swing.*;
 
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.Orange);
                    
                    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.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);
//            System.out.println("Dely");
        }
        catch (InterruptedException e) {
            System.out.println("Error sleeping");
        }
    }
 
}
 
 
 
 
 
 
 
 
 
 
import java.awt.*;
import java.util.Stack;
 
 
public class AlgoVisualizer {
 
    private static int DELAY = 10;
    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){
 
        // 初始化數(shù)據(jù)
        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);
        
        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);  //find the path from the final position
        		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);
    }
    
    public 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 = "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 N, M;
    private char[][] maze;
    
    private int entranceX, entranceY;
    private int exitX, exitY;
    
    public boolean[][] visited;  
    public boolean[][] path;
    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);
 
            // 讀取后續(xù)的N行
            maze = new char[N][M];
            visited = new boolean[N][M];
            path = new boolean[N][M];
            result = new boolean[N][M];
            
 
            
            
            for(int i = 0 ; i < N ; i ++){
                String line = scanner.nextLine();
 
                // 每行保證有M個(gè)字符
                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 ) {
		// TODO Auto-generated constructor stub
		this.x = x;
		this.y = y;
		this.prev = prev;
	}
	
	public Position(int x, int y) {
		// TODO Auto-generated constructor stub
		this(x, y, null);
	}
 
	
	public int getX() { return x;}
	public int getY() { return y;}
	public Position getPrev() {return prev;}
 
}

上面是深度優(yōu)先的非遞歸遍歷方法

下面是廣度優(yōu)先的遍歷方法

廣度優(yōu)先

實(shí)現(xiàn)效果

示例代碼

import java.awt.*;
import java.util.LinkedList;
import java.util.Stack;
 
 
public class AlgoVisualizer {
 
    private static int DELAY = 10;
    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){
 
        // 初始化數(shù)據(jù)
        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);
        
        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);  //find the path from the final position
        		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);
    }
    
    public 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 = "maze_101_101.txt";
 
        AlgoVisualizer vis = new AlgoVisualizer(mazeFile);
 
    }
}

知識(shí)點(diǎn)總結(jié)

q為抽象的隊(duì)列

以上就是Java分別利用深度優(yōu)先和廣度優(yōu)先求解迷宮路徑的詳細(xì)內(nèi)容,更多關(guān)于Java求解迷宮路徑的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • Java如何通過(guò)反射方式生成數(shù)據(jù)庫(kù)實(shí)體類(lèi)

    Java如何通過(guò)反射方式生成數(shù)據(jù)庫(kù)實(shí)體類(lèi)

    這篇文章主要介紹了Java如何通過(guò)反射方式生成數(shù)據(jù)庫(kù)實(shí)體類(lèi)問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-12-12
  • java開(kāi)發(fā)SpringBoot參數(shù)校驗(yàn)過(guò)程示例教程

    java開(kāi)發(fā)SpringBoot參數(shù)校驗(yàn)過(guò)程示例教程

    這篇文章主要為大家介紹了SpringBoot如何進(jìn)行參數(shù)校驗(yàn)的過(guò)程示例詳解教程,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步
    2021-10-10
  • springboot lua檢查redis庫(kù)存的實(shí)現(xiàn)示例

    springboot lua檢查redis庫(kù)存的實(shí)現(xiàn)示例

    本文主要介紹了springboot lua檢查redis庫(kù)存的實(shí)現(xiàn)示例,為了優(yōu)化性能,通過(guò)Lua腳本實(shí)現(xiàn)對(duì)多個(gè)馬戲場(chǎng)次下的座位等席的庫(kù)存余量檢查,感興趣的可以了解一下
    2024-09-09
  • Java求兩集合的交集、并集、差集實(shí)例

    Java求兩集合的交集、并集、差集實(shí)例

    這篇文章主要介紹了Java求兩集合的交集、并集、差集實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-08-08
  • java實(shí)現(xiàn)代碼統(tǒng)計(jì)小程序

    java實(shí)現(xiàn)代碼統(tǒng)計(jì)小程序

    這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)代碼統(tǒng)計(jì)小程序,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2019-09-09
  • java使用OGEngine開(kāi)發(fā)2048

    java使用OGEngine開(kāi)發(fā)2048

    眾所周知OGEngine是國(guó)人對(duì)AndEngine改進(jìn)后的國(guó)產(chǎn)Java編程的游戲引擎,除了支持3D游戲這個(gè)雞肋功能之外AndEngine的功能OGEngine都有,而且AndEngine缺少的多點(diǎn)觸摸功能也被國(guó)人完善了。今天我們就嘗試下使用OGEngine制作熱門(mén)游戲2048.
    2015-03-03
  • springboot讀取nacos配置文件的實(shí)現(xiàn)

    springboot讀取nacos配置文件的實(shí)現(xiàn)

    SpringBoot注冊(cè)服務(wù)到Nacos上,由Nacos來(lái)做服務(wù)的管理,本文主要介紹了springboot讀取nacos配置文件的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2022-05-05
  • SpringDataJpa like查詢(xún)無(wú)效的解決

    SpringDataJpa like查詢(xún)無(wú)效的解決

    這篇文章主要介紹了SpringDataJpa like查詢(xún)無(wú)效的解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-12-12
  • 淺談Java Fork/Join并行框架

    淺談Java Fork/Join并行框架

    這篇文章主要介紹了淺談Java Fork/Join并行框架,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2017-09-09
  • spring security登錄成功后跳轉(zhuǎn)回登錄前的頁(yè)面

    spring security登錄成功后跳轉(zhuǎn)回登錄前的頁(yè)面

    這篇文章主要介紹了spring security登錄成功后跳轉(zhuǎn)回登錄前的頁(yè)面,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-09-09

最新評(píng)論

黄浦区| 湄潭县| 呼伦贝尔市| 灌南县| 株洲市| 嘉定区| 开封县| 晋州市| 延庆县| 库伦旗| 深州市| 襄汾县| 文水县| 临西县| 呼伦贝尔市| 阳新县| 梅州市| 额敏县| 彰化市| 宣城市| 五台县| 特克斯县| 高雄市| 额济纳旗| 霍林郭勒市| 东港市| 嘉义市| 自治县| 县级市| 南召县| 蓝山县| 白山市| 清涧县| 定陶县| 潜山县| 铜山县| 美姑县| 盘锦市| 曲靖市| 东光县| 凤山县|