POJ3009 Curling 2.0(DFS+剪枝)

#include <iostream>

using namespace std;

#define  N  40
bool maze[N][N];
int dx[4] = {-1, 0, 1, 0};
int dy[4] = {0, 1, 0, -1};
int step = 0, minstep = 100, W, H;

struct point
{
	int pi, pj;
};
point st, end;

bool IsLegal(int li, int lj)
{
	if( li >= 0 && li < H && lj >= 0 && lj < W )
		return true;
	else
		return false;
}

void dexplor(int ei, int ej) // 深度探索
{
	step++;
	int ti = ei, tj = ej;
	int i, j;
	for(i = 0; i < 4; i++)
	{
		ti += dx[i];
		tj += dy[i]; 
		if( IsLegal(ti, tj) && maze[ti][tj] ) // 周围有空白地方才可以溜球
		{
			while( true ) 
			{
				if( ti == end.pi && tj == end.pj ) // 是目标点
				{
					if( step > 10 || step >= minstep ) break; // 提前结束
					minstep = step;
					break;
				}
				ti += dx[i];// 继续扩展
				tj += dy[i];
				if( IsLegal(ti, tj) )
				{
					if( !maze[ti][tj] ) // 碰到墙壁
					{
						if( step >= 10 || step >= minstep ) break; // 提前结束
						maze[ti][tj] = 1;
						dexplor(ti-dx[i], tj-dy[i]); // 从这个位置继续探索
						step--;     // 回溯
						maze[ti][tj] = 0;
						break;
					}
				}
				else
					break;
			}
			ti = ei, tj = ej;
		}
		else
		{
			ti = ei, tj = ej;
		}
	}
}

int main()
{
	// 168K  63MS 
	freopen("in.txt", "r", stdin);
	int i, j, ta;
	while( true )
	{
		scanf("%d %d\n", &W, &H);
		if( W == 0 && H == 0 ) break;
		memset(maze, 1, sizeof(maze) );
		for(i = 0; i < H; i++)
		{
			for(j = 0; j < W; j++)
			{
				scanf("%d", &ta);
				if( ta == 1 ) maze[i][j] = false;
				if( ta == 2 )
				{
					st.pi = i; 
					st.pj = j;
				}
				if( ta == 3 )
				{
					end.pi = i; 
					end.pj = j;
				}
			}
		}
		dexplor(st.pi, st.pj);
	//	if( minstep == 0 ) minstep = 1;
		if( minstep == 100 ) printf("-1\n");
		else printf("%d\n", minstep);

		step = 0;
		minstep = 100;
	}
	return 0;
}


 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值