我去啊。。开始用C的DFS写的。。直接TLE了,发现这题不能用DFS,只能BFS。。好吧,C没有队列用起来真心不方便,只能全用JAVA重写。。坑死我了,浪费了近两小时。。
import java.util.LinkedList;
import java.util.Scanner;
public class Main
{
static int L, R, C;
static char a[][][] = new char[30][30][30];
static int dir[][] = { { 0, -1, 0 }, { 0, 1, 0 }, { 0, 0, -1 },
{ 0, 0, 1 }, { -1, 0, 0 }, { 1, 0, 0 } };
static class Position
{
int time;
int l;
int r;
int c;
}
static int bfs(Position start)
{
LinkedList<Position> queue = new LinkedList<Position>();
queue.addLast(start);
while (!queue.isEmpty())
{
Position p = queue.removeFirst();
for (int i = 0; i < dir.length; i++)
{
int tl = p.l + dir[i][0];
int tr = p.r + dir[i][1];
int tc = p.c + dir[i][2];
if (tl >= 0 && tl < L && tr >= 0 && tr < R && tc >= 0
&& tc < C && a[tl][tr][tc] != '#')
{
if (a[tl][tr][tc] == 'E')
return p.time + 1;
else
{
a[tl][tr][tc] = '#';
Position pp = new Position();
pp.l = tl;
pp.r = tr;
pp.c = tc;
pp.time = p.time + 1;
queue.addLast(pp);
}
}
}
}
return -1;
}
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int sl = 0, sr = 0, sc = 0;
while (true)
{
String size = scanner.nextLine();
String[] ss = size.split(" ");
L = Integer.parseInt(ss[0]);
R = Integer.parseInt(ss[1]);
C = Integer.parseInt(ss[2]);
if (L == 0 && R == 0 && C == 0)
break;
for (int i = 0; i < L; i++)
{
for (int j = 0; j < R; j++)
{
String line = scanner.nextLine();
int k = 0;
for (char ch : line.toCharArray())
{
a[i][j][k] = ch;
if (ch == 'S')
{
sl = i;
sr = j;
sc = k;
a[i][j][k] = '#';
}
k++;
}
}
scanner.nextLine();
}
Position start = new Position();
start.l = sl;
start.r = sr;
start.c = sc;
start.time = 0;
int res = bfs(start);
if (res != -1)
System.out.format("Escaped in %d minute(s).\n", res);
else
System.out.println("Trapped!");
}
scanner.close();
}
}