拯救行动 —— bfs + 优先队列

本文介绍了如何通过结合广度优先搜索(BFS)和优先队列来解决‘拯救行动’问题。初始方法仅考虑路径长度,但忽略了时间成本。通过优先队列可以找到花费时间最短的最短路径,例如在@example中,用7个单位时间的路径实际上可以缩短到6个单位时间。

在这里插入图片描述在这里插入图片描述样例输入1

7 8
#@#####@
#@a#@@r@
#@@#x@@@
@@#@@#@#
#@@@##@@
@#@@@@@@
@@@@@@@@

样例输出1

13

样例输入2

13 40
@x@@##x@#x@x#xxxx##@#x@x@@#x#@#x#@@x@#@x
xx###x@x#@@##xx@@@#@x@@#x@xxx@@#x@#x@@x@
#@x#@x#x#@@##@@x#@xx#xxx@@x##@@@#@x@@x@x
@##x@@@x#xx#@@#xxxx#@@x@x@#@x@@@x@#@#x@#
@#xxxxx##@@x##x@xxx@@#x@x####@@@x#x##@#@
#xxx#@#x##xxxx@@#xx@@@x@xxx#@#xxx@x#####
#x@xxxx#@x@@@@##@x#xx#xxx@#xx#@#####x#@x
xx##@#@x##x##x#@x#@a#xx@##@#@##xx@#@@x@x
x#x#@x@#x#@##@xrx@x#xxxx@##x##xx#@#x@xx@
#x@@#@###x##x@x#@@#@@x@x@@xx@@@@##@@x@@x
x#xx@x###@xxx#@#x#@@###@#@##@x#@x@#@@#@@
#@#x@x#x#x###@x@@xxx####x@x##@x####xx#@x
#x#@x#x######@@#x@#xxxx#xx@@@#xx#x#####@

样例输出2

7
思路:刚开始我对‘x’与‘@’处理的区别就是一个的深度多加1,测试后只能通过几组数据,其实我忽略一个问题就是:这样做出来的最短路径未必花费最短时间,比如:
@@@@@
rxxxxa
这个的最短路径需要花费7个单位时间,而显然我们只需花费6个单位时间就可以拯救公主。
还是需要借助数据结构优先队列解决。

import java.util.PriorityQueue;
import java.util.Scanner;

public class Main{
	static int [] dx =  {-1,0,0,1};
	static int [] dy = {0,-1,1,0};
	static int step = 1;
	static boolean flag = false;
	public static void main(String []args){
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int m = sc.nextInt();
		sc.nextLine();
		char [][]graph = new char[n][];
		int [][]vis = new int[n][m];
		for(int i=0;i<n;i++){
			graph[i] = sc.nextLine().toCharArray();
		}
		
		//创建队列
		PriorityQueue<Node> queue = new PriorityQueue<>();
		
		 for(int i=0;i<n;i++){
			 for(int j=0;j<m;j++){
			    if(graph[i][j] == 'r')  queue.add(new Node(i,j,0));
			 }
		 }
		
		 while(!queue.isEmpty()){
			 Node poll = queue.poll();
			 int x = poll.i;
			 int y = poll.j;
			 int deep = poll.depth;
			 vis[x][y] = 1;
			 
			 if(graph[x][y] == 'a'){
				 flag = true;
				 step = poll.depth;
				 break;
			 }
			 
			 for(int u=0;u<4;u++){
	    			int tx = x+dx[u] , ty = y+dy[u];    		
	    		  if(tx >=0 && tx < n  && ty>=0 && ty<m && graph[tx][ty] != '#' && vis[tx][ty] == 0){
	    			  vis[tx][ty] = 1;
	 				 if(graph[tx][ty] == 'x')  queue.add(new Node(tx,ty,deep+2));
	 				 else  queue.add(new Node(tx,ty,deep+1)); 
	    	       }
	    		}
		     }
		   if(flag == true) System.out.print(step);
		   else System.out.print("Impossible");
       }
	
	//将坐标与深度封装为一个类,并实现比较接口Comparable
	static class Node implements Comparable<Node>{
		int i;
		int j;
		int depth;
		
		public Node(int i,int j,int depth){
			this.i = i;
			this.j = j;
			this.depth = depth;  
		}
		
		//按照点的深度从小到大排序
		public int compareTo(Node o) {
			int x = this.depth - o.depth;
			if(x == 0)  return  this.depth - o.depth;
			else  return x;
		}
	}
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值