大意:
天使被MOLIGPY抓住了!他被Moligpy监禁了。监狱被描述为N * M(N,M <= 200)矩阵。监狱里有WALL,ROAD和GUARD。
天使的朋友想要拯救天使。他们的任务是:接近天使。我们假设“接近天使”是为了达到安吉尔留下的位置。当网格中有一名后卫时,我们必须杀死他(或她?)才能进入网格。我们假设我们向上,向下,向右,向左移动需要1个单位时间,并且杀死一名守卫也需要1个单位时间。我们足够强大,可以杀死所有的守卫。
你必须计算接近天使的最短时间。(当然,我们只能将UP,DOWN,LEFT和RIGHT移动到绑定范围内的邻居网格。)
输入
第一行包含两个整数代表N和M.
然后是N行,每行有M个字符。“.” 代表道路,“a”代表Angel,“r”代表Angel的每个朋友。 处理到文件的末尾。
输出
对于每个测试用例,您的程序应输出一个整数,代表所需的最短时间。如果这样的数字不存在,你应该输出一行包含“贫穷的ANGEL必须终生留在监狱里”。
求最短,自然想到用bfs,每个点都有权重?那可以考虑下优先队列。因为题目的意思也没有保证天使的朋友有多少个,所以不如让朋友找天使,不如反过来,从天使出发,找最近的朋友。做过了这题UVA 11624 Fire!对于多点bfs,也可以让多个朋友找天使的,把所有朋友放进队列,再开始bfs,注意!!这里以为只是输入一组数据,WA几次才发现不止一组,可是样例给的是一组,坑啊~~
import java.util.PriorityQueue;
import java.util.Scanner;
public class hdu1242 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while(in.hasNext()) {
n = in.nextInt();
m = in.nextInt();
ch = new char[n+5][m+5];
vis = new boolean[n+5][m+5];
pq.clear();
for(int i=0;i<n;i++)
ch[i] = in.next().toCharArray();
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
if(ch[i][j]=='a') {
pq.add(new Node(i, j, 0));
vis[i][j] = true;
}
int ans = bfs();
if(ans==-1)
System.out.println("Poor ANGEL has to stay in the prison all his life.");
else
System.out.println(ans);
}
}
static int n,m;
static boolean[][] vis;
static char[][] ch;
static int[] dx = new int[] {1,0,-1,0};
static int[] dy = new int[] {0,1,0,-1};
static PriorityQueue<Node> pq = new PriorityQueue<>();
static int bfs() {
while(!pq.isEmpty()) {
Node u = pq.poll();
if(ch[u.x][u.y]=='r')
return u.t;
for(int i=0;i<4;i++)
if(ok(u.x+dx[i],u.y+dy[i])) {
if(ch[u.x+dx[i]][u.y+dy[i]]=='x')
pq.add(new Node(u.x+dx[i],u.y+dy[i],u.t+2));
else
pq.add(new Node(u.x+dx[i],u.y+dy[i],u.t+1));
vis[u.x+dx[i]][u.y+dy[i]] = true;
}
}
return -1;
}
static boolean ok(int x,int y) {
return x>=0 && x<n && y>=0 && y<m && ch[x][y]!='#' && !vis[x][y];
}
static class Node implements Comparable<Node>{
int x,y,t;
public Node(int x,int y,int t) {
this.x = x;
this.y = y;
this.t = t;
}
@Override
public int compareTo(Node o) {
return this.t - o.t;
}
}
}