Fork me on GitHub

3894.迷宫问题 BFS


这道题求路径 可不可通很容易
这道题主要是求具体路线比较麻烦 所以我是采用递归 因为每一步都阶进1
所以我采用递归的方式 因为只有一条具体路线所以不怕 用递归

 
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 int  [][] arr   = new int[5][5];
	static int [][] dis    = new int[5][5];;
	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 sx = 0, sy = 0, gx = 4, gy = 4;
		while(sc.hasNext()) {
			for (int i = 0; i < 5; i++) { 	      		// 输入 以及得到sx sy 的地址
				for (int x = 0; x < 5; x++) {
					dis[i][x] = INF; 		          		// 把所有位置初始化为INF 初始化
					arr[i][x] = sc.nextInt();
			}
		}
		dis[sx][sy] = 0;						              //将起点设置为 0
		Queue<P> que = new LinkedList<P>();		//创建一个队列
		que.offer(new P(sx, sy));		     		//直接扔到队列里面
		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 <5 && ny >= 0 && ny < 5 && dis[nx][ny] == INF && arr[nx][ny] != 1) {
					que.offer(new P(nx, ny));
					dis[nx][ny] = dis[p.x][p.y] + 1;
				}
			}
		}
		print(dis,gx,gy);
	}	
}
 
	private static void print(int[][] dis2,int x ,int y ) {
		if(x==0&&y==0) {
//			System.out.println("("+x+","+y+")");
		}
		for(int i = 0 ; i<4 ;i++) {
			int nx = x + tempx[i];
			int ny = y + tempy[i];
			if(nx >= 0 && nx <5 && ny >= 0 && ny < 5 && dis[nx][ny] == dis2[x][y]-1) {
				print(dis2,nx,ny);
				System.out.println("("+x+", "+y+")");
			}
		}
	}
}
posted @ 2019-07-07 22:22  cznczai  阅读(135)  评论(0编辑  收藏  举报