迷宫问题 BFS+路径

/*定义一个二维数组: 

int maze[5][5] = {

    0, 1, 0, 0, 0,

    0, 1, 0, 1, 0,

    0, 0, 0, 0, 0,

    0, 1, 1, 1, 0,

    0, 0, 0, 1, 0,
};

它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。
Input
一个5 × 5的二维数组,表示一个迷宫。数据保证有唯一解。
Output
左上角到右下角的最短路径,格式如样例所示。
Sample Input
0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0
Sample Output
(0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 4)
(4, 4)
/
*
*题目解析:  最短路径问题——>广度优先搜索
* 结构体 记录 最短路径
import java.util.*;

public class Main{
    static int[][] dir = {{0,1},{0,-1},{1,0},{-1,0}};
    static boolean[][] vis;
    static int[][] maze;
    
    static class node{
        int x;
        int y;
        String path;
        public node(int x,int y,String path) {
            this.x = x;
            this.y = y;
            this.path = path;
        }
    }
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        Queue<node> queue = new LinkedList<node>();
        
        vis = new boolean[5][5];
        maze = new int[5][5];
        
        for(int i=0;i<5;i++)
            for(int j=0;j<5;j++)
                maze[i][j] = scanner.nextInt();
        
        vis[0][0] = true;
        queue.add(new node(0, 0, "(0, 0)"));
        
        while(!queue.isEmpty()) {
            node temp = queue.poll();
            for(int i=0;i<4;i++) {
                int xx = temp.x + dir[i][0];
                int yy = temp.y + dir[i][1];
                if(xx>=0&&xx<5&&yy>=0&&yy<5&&!vis[xx][yy]&&maze[xx][yy]==0) {
                    vis[xx][yy] = true;
                    queue.add(new node(xx, yy, temp.path+"
("+xx+", "+yy+")"));  //通过与上一个元素路径的衔接,记录最短路径
                    if(xx==4&&yy==4) {
                        System.out.println(temp.path+"
("+xx+", "+yy+")");
                        break;
                    }       
                } 
            }
        }

    }
}


 


 
原文地址:https://www.cnblogs.com/Lemon1234/p/10596407.html