bfs_迷宫求最短路径

宽度优先搜索按照距离开始状态由近及远的顺序进行搜索,可以很容易用来求解最短路径或者最少操作等问题。

将已经访问过的状态用标记管理起来,便可以很好地做到由近及远的搜索。

import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class Main {
    static int n,m;
    static char[][] maze;
    static int [][] dis;
    final static int INF = 100000000;
    static int gx,gy;
    static int sx,sy;
    
    static int dx[] = new int[]{1,0,-1,0};
    static int dy[] = new int[]{0,1,0,-1};
    
    static int bfs(){
        
        Queue<Pair> queue = new LinkedList();
        
        for(int i = 0; i < n; i++){
            for(int j = 0; j < m; j++)
                dis[i][j] = INF;
        }

        queue.add(new Pair(sx,sy));
        dis[sx][sy] = 0;
        
        while(!queue.isEmpty()){
            Pair p = queue.remove();
            System.out.println(p.x + " "+ p.y);
            if(p.x == gx && p.y == gy) break;
            
            for(int i = 0; i < 4; i++){
                int nx = p.x + dx[i]; 
                int ny = p.y + dy[i];
                if(0 <= nx && nx < n && 0 <= ny && ny < m && maze[nx][ny] != '#' && dis[nx][ny] == INF){
                    queue.add(new Pair(nx,ny));
                    dis[nx][ny] = dis[p.x][p.y] + 1;
                }    
            }
        }
        
        return dis[gx][gy];
    
    }
    

    public static void main(String[] args) {
        
        Scanner in = new Scanner(System.in);
        n = in.nextInt();
        m = in.nextInt();
        maze = new char[n][m];
        dis = new int[n][m];
        
        for(int i = 0; i < n; i++){
            for(int j = 0; j < m; j++){
                maze[i][j] = in.next().charAt(0);
                if(maze[i][j] == 'S'){
                    sx = i;
                    sy = j;
                }
                if(maze[i][j] == 'G'){
                    gx = i;
                    gy = j;
                }
            }
                
        }
        
        
        System.out.println(bfs());
        
        
    


    }

}


class Pair{
    public Pair(int x, int y){
        this.x = x; this.y = y;
    }
    int x;
    int y;
}
原文地址:https://www.cnblogs.com/cjshuang/p/6653528.html