HDU 1010 - Tempter of the Bone 奇偶剪枝+深搜

HDU 1010 - Tempter of the Bone

题意:

在一个迷宫中,小狗的位置为 S ,出口的位置在 D ,出口只有在第 t 秒时才会开门让小狗出去。x 为不能走的的位置(小狗在任意一个位置停留时间不能大于等于 1 秒,因为到达1秒那个位置会下降)。求小狗能否走出迷宫

思路:

简单的 dfs+奇偶剪枝

第一次学奇偶剪枝。。。不会的可以看这篇博客:迷宫中回溯法的剪枝——奇偶剪枝


import java.util.*;

public class Main {

	static int n,m,t;
	static boolean[][] vis = new boolean[10][10];
	static char[][] s = new char[10][10];
	static int[][] a = {
			{-1,0},{1,0},{0,-1},{0,1}
	};		
	static boolean val = false;
	static int x1 = 0,y1 = 0;
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner cin = new Scanner(System.in);
		int x = 0,y = 0;
		
		while(cin.hasNext())
		{
			int k = 0;
			n = cin.nextInt();
			m = cin.nextInt();
			t = cin.nextInt(); 
			if(n+m+t == 0)
				break;
			for(int i=0;i<n;i++)
			{
				String str = cin.next();
				s[i] = str.toCharArray();
			}
			
			for(int i=0;i<n;i++)
			{
				for(int j=0;j<m;j++)
				{
					vis[i][j] = false;
					if(s[i][j]=='S')
					{
						x=i;
						y=j;
					}
					else if(s[i][j]=='D')
					{
						x1 = i;
						y1 = j;
					}
					else if(s[i][j]=='X')
						k++;
				}
			}
			if(t >= n*m-k|| Math.abs(x1-x)+Math.abs(y1-y) > t)
			{
				System.out.println("NO");
				continue;
			}
			val = false;
			vis[x][y] = true;
			dfs(x,y,0);
			if(val)
				System.out.println("YES");
			else
				System.out.println("NO");
		}
	}
	public static void dfs(int x,int y,int k)
	{
		if(k>t)
			return ;
		//System.out.println(x+" "+y+" "+k);
		if(s[x][y]=='D' && k==t)
		{
			val = true;
			return ;
		}
		int w = t-k+Math.abs(x1-x)+Math.abs(y1-y);
        //剩余的步数与目前位置到终点的最短步数奇偶性相同时,才有可能恰好在t时刻到大门的地方
		if(w%2==1)  //检验奇偶性是否相同
			return ;
		for(int i=0;i<4;i++)
		{
			int xx = x+a[i][0];
			int yy = y+a[i][1];
			if(xx<0 || xx >=n || yy <0 || yy>=m)
				continue;
			if(vis[xx][yy]==false && s[xx][yy]!='X')
			{
				vis[xx][yy] = true;
				dfs(xx,yy,k+1);
				vis[xx][yy] = false;
				if(val)
					return ;
			}
			
		}
		return ;
	}

}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值