HDOJ 1010 Tempter of the bone

🍑 OJ专栏


🍑 HDOJ 1010 Tempter of the bone

在这里插入图片描述
输入

4 4 5
S.X.
..X.
..XD
....
3 4 5
S.X.
..X.
...D
0 0 0

输出

NO
YES

🙈 本想着 BFS 找到最短时间,只要最短时间 < T 理论上是可以的……奈何要考虑的情况过多……

🍑 思路

🍤 DFS搜出到达终点的所有时间,判断时间是否符合条件
🍤 剪枝:奇偶剪枝(起点与终点的曼哈顿距离奇偶性 与 要走的步数 相同

🍑 AC

import java.util.*;

public class N1010骨头的诱惑
{
	static int N = 10, n, m, T;
	static char[][] g = new char[N][N];
	static boolean[][] st = new boolean[N][N];
	static int[] dx = { 1, 0, -1, 0 };
	static int[] dy = { 0, 1, 0, -1 };

	public static void main(String[] args)
	{
		Scanner sc = new Scanner(System.in);
		while (sc.hasNext())
		{
			n = sc.nextInt();
			m = sc.nextInt();
			T = sc.nextInt();
			if (n == 0 && m == 0 && T == 0)
				break;
//			x,y 记录终点坐标
			int x = 0;
			int y = 0;
//			xx,yy 记录终点坐标
			int xx = 0;
			int yy = 0;
			for (int i = 0; i < n; i++)
			{
				char[] arr = sc.next().toCharArray();
				for (int j = 0; j < m; j++)
				{
					g[i][j] = arr[j];
					if (g[i][j] == 'S')
					{
						x = i;
						y = j;
					}
					if (g[i][j] == 'D')
					{
						xx = i;
						yy = j;
					}
				}
			}
			for (int i = 0; i < N; i++)
				Arrays.fill(st[i], false);
			st[x][y] = true;
			// 逻辑运算符的断路效果,判断距离是否有解,必须放在前边才可以实现剪枝效果
			if (dis(x, y, xx, yy, T) && dfs(x, y, 0))
				System.out.println("YES");
			else
			{
				System.out.println("NO");
			}

		}
	}
	//传说中的奇偶剪枝
	private static boolean dis(int x, int y, int xx, int yy, int t)
	{
		int tt = Math.abs(xx - x) + Math.abs(yy - y);//起点和终点的曼哈顿距离
		if (Math.abs(tt - t) % 2 == 0)// 曼哈顿距离 与 目标时间t 的奇偶性要相同才是有解距离
			return true;

		return false;
	}

	private static boolean dfs(int x, int y, int t)
	{
		if (t > T)
			return false;
		if (g[x][y] == 'D' && t == T)
			return true;
		for (int i = 0; i < 4; i++)
		{
			int xx = x + dx[i];
			int yy = y + dy[i];
			if (xx < 0 || xx >= n || yy < 0 || yy >= m || st[xx][yy] || g[xx][yy] == 'X')
				continue;
			st[xx][yy] = true;
			if (dfs(xx, yy, t + 1))
				return true;
			st[xx][yy] = false;
		}
		return false;
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值