zoukankan      html  css  js  c++  java
  • 迷宫的最短路径--BFS

    import java.util.LinkedList;
    import java.util.Queue;
    import java.util.Scanner;
    class P {
    	int x;
    	int y;
    	public P(int a, int b) {
    		this.x = a;
    		this.y = b;
    	}
    }
    public class Main {
    	static final int INF = -1;
    	static char[][] arr;
    	static int[][] dis;
    	static int[] tempx = { 1, 0, -1, 0 };
    	static int[] tempy = { 0, 1, 0, -1 };
    	public static void main(String[] args) {
    		Scanner sc = new Scanner(System.in);
    		int N = sc.nextInt();
    		int M = sc.nextInt();
    		int sx = 0, sy = 0, gx = 0, gy = 0;
    		arr = new char[N][M];
    		dis = new int[N][M];
    		for (int i = 0; i < N; i++) { 		                  	// 输入 以及得到sx sy 的地址
    			String str = sc.next();
    			arr[i] = str.toCharArray();
    			for (int x = 0; x < str.length(); x++) {
    				dis[i][x] = INF; 			                               	// 把所有位置初始化为INF 初始化
    				if (str.charAt(x) == 'S') {	
    					sx = i;
    					sy = x;
    				}
    				if (str.charAt(x) == 'G') {
    					gx = i;
    					gy = x;
    				}
    			}
    		}
    		dis[sx][sy] = 0;			                                          			//将起点设置为 0
    		Queue<P> que = new LinkedList<P>();		            //创建一个队列
    		que.offer(new P(sx, sy));			                              	//直接扔到队列里面
    //		System.out.println(sx + " " + sy + " " + gx + " " + gy);
    		while (que.size() > 0) {
    			P p = que.poll();				                                          	//poll队列的头
    			if (p.x == gx && p.y == gy)		                               	//到达终点跳出来
    				break;
     
    			for (int i = 0; i < 4; i++) {		                                   //四个方向
    				int nx = p.x + tempx[i];
    				int ny = p.y + tempy[i];
     
    				if (nx >= 0 && nx < N && ny >= 0 && ny < M && dis[nx][ny] == INF && arr[nx][ny] != '#') {
    					que.offer(new P(nx, ny));
    					dis[nx][ny] = dis[p.x][p.y] + 1;
    				}
    			}
    		}
    		System.out.println(dis[gx][gy]);
    	}
    }
    
  • 相关阅读:
    java并发:简单面试问题集锦
    Java:泛型
    Java:注解(元数据)
    Java:反射
    Java:静态代理 and 动态代理
    华为机试题——该警醒了,骚年
    java并发:线程同步机制之Lock
    java并发:中断一个正在运行的线程
    java中String类型变量的赋值问题
    java中的自增问题
  • 原文地址:https://www.cnblogs.com/cznczai/p/11148152.html
Copyright © 2011-2022 走看看