算法16 啊哈算法 广度优先搜索( Breadth First Search, BFS) 迷宫问题 JAVA

广度优先:每一步都列出所有可能

题目

迷宫由n 行m 列的单元格组成( n 和m 都=<50 ) ,每个单元格要么是空地, 要么
是障碍物。你的任务是帮助小哼找到一条从迷宫的起点通往小哈所在位置的最短路径。注意
障碍物是不能走的,当然小哼也不能走到迷宫之外。

代码

添加了个打印路线的功能
输出如图

简化为矩阵,障碍为1,终点为2.


//图形矩阵,障碍物,终点最短步数
/*
00000
00110
01200
00000
 */

class Main{
    public static void main(String[] args) {
        int x,y,m_s=99;
//队列 x,y,step
        int[] ax=new int[50];
        int[] ay=new int[50];//ay=ax;//que
        int[] as=new int[50];
//set map
        int[][] map=new int[][]{{0,0,0,0,0},{0,0,1,1,0},{0,1,2,0,0},{0,0,0,0,0}};
//walked places
        int [][] road=new int[4][5];
//4ways-move
        int [][] walk=new int[][]{{0,1},{0,-1},{1,0},{-1,0}};//4ways-move
//pointers
        int tail=1,head=0;
        
        for (;head<tail;) {//one point 4 ways
            for (int i = 0; i < 4; i++) {//head->tail
                x = ax[head] + walk[i][0];
                y = ay[head] + walk[i][1];
                //越界
                if (x > 3 || y > 4||x<0||y<0) {
                    continue;
                }
//check destination  
                if (map[x][y] == 2&&as[tail-1]<m_s) {
                    m_s=as[tail-1];
                    //origin
                    plot(map,road);
                    System.out.println(as[tail-1]);
                    break;
                }
                if (road[x][y] == 1) {//走过
                    continue;
                }

                if ((x == 1 && (y == 2 || y == 3)) || (x == 2 && y == 1)) {//障碍
                    continue;
                }
                ax[tail] = x;
                ay[tail] = y;
                as[tail]=as[head]+1;//!!!!!!!!!!!!!!!

                tail++;
                road[x][y] = 1;
            }
            head++;
        }    }
//添加了个打印路线的功能
    void plot(int map[][],int road[][]){
        for (int ix=0;ix<4;ix++){
            for (int j=0;j<5;j++){
                System.out.print(map[ix][j]);

            }
            System.out.println();
        }
        System.out.println();
        //road
        for (int ix=0;ix<4;ix++){
            for (int j=0;j<5;j++){
                System.out.print(road[ix][j]);
            }
            System.out.println();
        }
    }


}

原文地址:https://www.cnblogs.com/impw/p/15536261.html