ZOJ-1940

我去啊。。开始用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();
	}
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值