「日常训练」 Fire!(UVA-11624)
与其说是训练不如说是重温。重新写了Java版本的代码。
import java.util.*;
import java.math.*;
import java.io.BufferedInputStream;
public class Main
{
static class Node
{
int r, c, t;
public Node(int _r, int _c)
{
this(_r, _c, 0);
}
public Node(int _r, int _c, int _t)
{
r=_r; c=_c; t=_t;
}
}
static int[][] fireTime = new int[1005][1005];
static int[][] maze = new int[1005][1005];
static Queue<Node> q = new LinkedList<>();
static final int[] dx = {0,1,0,-1};
static final int[] dy = {1,0,-1,0};
static int r, c;
static int startR, startC;
static void getFireTime()
{
for(int i=0;i<=r;++i)
for(int j=0;j<=c;++j)
fireTime[i][j]=0x3f3f3f3f;
while(!q.isEmpty())
{
Node node = q.poll();
fireTime[node.r][node.c] = node.t;
for(int i=0; i!=4; ++i)
{
int tr = node.r + dx[i],
tc = node.c + dy[i];
if(tr>=0 && tr<r && tc>=0 && tc<c && fireTime[tr][tc]>node.t+1 && maze[tr][tc]==1)
{
fireTime[tr][tc] = node.t+1;
q.offer(new Node(tr, tc, node.t+1));
}
}
}
}
static String solve()
{
Queue<Node> sq = new LinkedList<>();
boolean[][] vis = new boolean[1005][1005];
sq.offer(new Node(startR, startC));
vis[startR][startC]=true;
while(!sq.isEmpty())
{
Node now = sq.poll();
if(now.t>=fireTime[now.r][now.c]) continue;
if(now.r==0 || now.r == r-1 || now.c == 0 || now.c == c-1)
return String.valueOf(now.t+1);
for(int i=0;i!=4;++i)
{
int tr = now.r + dx[i],
tc = now.c + dy[i];
if(tr>=0 && tr<r && tc>=0 && tc<c && fireTime[tr][tc]>now.t+1 && (!vis[tr][tc]) && maze[tr][tc]==1)
{
vis[tr][tc]=true;
sq.offer(new Node(tr, tc, now.t+1));
}
}
}
return "IMPOSSIBLE";
}
public static void main(String args[])
{
Scanner cin = new Scanner(new BufferedInputStream(System.in));
int T = cin.nextInt();
while(T-- != 0)
{
q.clear();
r = cin.nextInt();
c = cin.nextInt();
for(int i=0; i!=r; ++i)
{
String str = cin.next();
for(int j=0;j!=c;++j)
{
char chr = str.charAt(j);
if(chr == '#') maze[i][j] = 0;
else if(chr == '.') maze[i][j] = 1;
else if(chr == 'J')
{
maze[i][j] = 1;
startR=i; startC=j;
}
else if(chr == 'F')
{
maze[i][j] = 1;
q.offer(new Node(i,j));
}
}
}
getFireTime();
System.out.println(solve());
}
}
}
如非注明,原创内容遵循GFDLv1.3发布;其中的代码遵循GPLv3发布。