广度优先算法--迷宫问题

遍历过程

与深度优先算法不同的是,广度优先算法是先遍历层级在前的元素再遍历层级在后的元素,即再遍历完第一层元素后,再依次遍历第二层元素,依次类推。
而深度优先算法是从一个节点出发依次遍历下一层节点直到节点之后没有后继元素。

经典迷宫问题

定义一个二维数组:

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

/** * All rights reserved,designed By Echo * * @author: Echo * @createtime:2018/10/26 * @description:${DETAILS} **/
public class Main{
   // static MainB pre;
    static  Queue<Node> queue=new PriorityQueue<Node>();
    static  int [][]maze=new int[10][10];
    static int N=5;
    static int [][]der={{0,1},{1,0},{0,-1},{-1,0}};
    static int[][] vist=new int[10][10];
    static List<Node> res_path=new ArrayList<Node>();
    static void bfs(){
        Node head=new Node(0,0,null);
        Node p=head;
        queue.add(p);
        int j=0;
        while (p!=null){
            if(p.x==N-1&&p.y==N-1) break;
            for(int i=0;i<4;i++){
                int nx=p.x+der[i][0];
                int ny=p.y+der[i][1];
                if(nx<0||ny<0||nx>=N||ny>=N||maze[nx][ny]!=0||vist[nx][ny]!=0) continue;
               // System.out.println(nx+" "+j++);
                vist[nx][ny]=1;
                queue.add(new Node(nx,ny,p));
            }
           p=queue.poll();
        }
        while(p!=null){
            res_path.add(p);
            p=p.pre;
        }
    }
    static void generate(){
        Scanner in=new Scanner(System.in);
        for(int i=0;i<N;i++){
            for(int j=0;j<N;j++){
                maze[i][j]=in.nextInt();
                vist[i][j]=0;
            }
        }
    }
    static void print(){
        for(int i=res_path.size()-1;i>=0;i--){
            System.out.println("("+res_path.get(i).x+", "+res_path.get(i).y+")");
        }
    }
    public static void main(String []args){
        generate();
        bfs();
        print();
    }
}
/** * All rights reserved,designed By Echo * * @author: Echo * @createtime:2018/10/26 * @description:${DETAILS} **/
class Node implements Comparable<Node>{
    int x;
    int y;
    Node pre;
    public Node(int x,int y,Node pre){
        this.x=x;
        this.y=y;
        this.pre=pre;
    }

    @Override
    public int compareTo(Node o) {
        return 0;
    }

}
    原文作者:迷宫问题
    原文地址: https://blog.csdn.net/weixin_41597774/article/details/83420937
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞