zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    [ZZ]为什么选择傲游
    重新启用ClustrMaps记数
    Ubuntu 10.4的wubi安装BUG修正了
    [转载]关于C++,我觉得好的设计法则
    迅雷5.9.19.1390会员破解与快车旋风专用链补丁
    VS2010 Ultimate英文版下载
    不会“思维”只会“批判”,谨防网络舆论“怨妇化”
    游戏制作人(调侃)
    Visual Studio 2010 Beta安装感受
    msdev & devenv 的命令行用法
  • 原文地址:https://www.cnblogs.com/cjshuang/p/6653528.html
Copyright © 2011-2022 走看看