[百练]4116 拯救行动

广搜加优先队列

import java.util.Arrays;
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Scanner;

public class Main {
	static int n,m;
	static int max_n=205,max_m=205;
	static int[][] to= {{1,0},{-1,0},{0,1},{0,-1}};
	static char[][] ch=new char[max_n][max_m];
	static boolean[][] vis=new boolean[max_n][max_m];
	static Node qishi=new Node();
	static Node gongzhu=new Node();
	static int min;
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc=new Scanner(System.in);
		int s=sc.nextInt();
		while(s-->0) {
			
			n=sc.nextInt();
			m=sc.nextInt();
			for(int i=0;i<n;i++) {
				Arrays.fill(vis[i], false);
				String str=sc.next();
				if(str.contains("r")) {
					qishi.x=i;
					qishi.y=str.indexOf('r');
					qishi.score=0;
				}
//				else if(str.contains("a")){
//					gongzhu.x=i;
//					gongzhu.y=str.indexOf('a');
//				}
				ch[i]=str.toCharArray();
			}
			int res=bfs();
			
			System.out.println(res==-1?"Impossible":res);
		}

	}
	private static int bfs() {
		min=1000000;
		// TODO Auto-generated method stub
		Comparator<Node> cmp=new Comparator<Node>() {
			
			@Override
			public int compare(Node o1, Node o2) {
				// TODO Auto-generated method stub
				return o1.score-o2.score;
			}
		};
		PriorityQueue<Node> que=new PriorityQueue<Node>(cmp);
//		Queue<Node> que=new LinkedList<Node>();
		que.add(qishi);
		vis[qishi.x][qishi.y]=true;
//		boolean flag=false;
		while(!que.isEmpty()) {
			Node node=que.poll();
			if(ch[node.x][node.y]=='a') {
				return node.score;
			}else {
				for(int i=0;i<4;i++) {
					int a=node.x+to[i][0];
					int b=node.y+to[i][1];
					if(a>=0&&a<n&&b>=0&&b<m&&!vis[a][b]) {
						vis[a][b]=true;
						if(ch[a][b]=='@') {
							que.add(new Node(a, b, node.score+1));
						}else if(ch[a][b]=='x') {
							que.add(new Node(a, b, node.score+2));
						}else if(ch[a][b]=='a') {
//							flag=true;
//							min=Math.min(min, node.score+1);
							que.add(new Node(a, b, node.score+1));
							continue;
						}else {
							continue;
						}
					}
				}	
			}
		}
		return -1;
	}

}
class Node{
	int x;
	int y;
	int score;
	public Node() {
		
	}
	public Node(int x,int y,int score) {
		this.x=x;
		this.y=y;
		this.score=score;
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值