HDU 2531 搜索

以左上角坐标 为参考。

每次移动要判断整个身体所在的位置 是否满足可移动 条件


/*  
 *problem ID: HDU 2531
 * Author ID: fuqiang11  
 *      TIME: 2013-07-20  
 * Algorithm: 搜索 BFS  
 *    Status: (Accept)  
*/  
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <queue>
#define maxn 100
using namespace std;

char map[maxn][maxn];
struct point
{
	int x;
	int y;
	//point(int a, int b){ x = a, y = b; }
	//point(){};
}st,ed;
point DPlayer[22];  //防守员
int step[maxn][maxn]; //移动步数
int N,M,PlayerNum; //PlayerNum 防守员身体占的位置集合的个数
int LposX,LposY; //左上角坐标
int xx[] = {0,0,1,-1};
int yy[] = {1,-1,0,0};
 
int check(int x, int y) //判断是否可以移动。 
{
	if(step[x][y] != -1) return 0;
	for(int i = 0; i < PlayerNum; i++)
	{
		int r = x - LposX + DPlayer[i].x; //左上角点横坐标改变的位置 + 原坐标 = 现坐标 
		int c = y - LposY + DPlayer[i].y; //。。。。纵。。。。。 
		if(r<0 || r>N-1 || c<0 || c>M-1) return 0; //超过边界 
		if(map[r][c] == 'O') return 0;   //遇到 守卫 
	}
	for(int i = 0; i < PlayerNum; i++)
	{
		int r = x - LposX + DPlayer[i].x; //左上角点横坐标改变的位置 + 原坐标 = 现坐标 
		int c = y - LposY + DPlayer[i].y; //。。。。纵。。。。。 
		if(map[r][c] == 'Q') return 2; //抓到 四分卫 
	}
	return 1; //可以移动 
}
int BFS(int stx, int sty)
{
	if(LposX == -1)	return -1;
	memset(step,-1,sizeof(step));
	queue <point> q;
	st.x = stx; st.y = sty;
	q.push(st);
	step[stx][sty] = 0;
	while(!q.empty())
	{
		st = q.front();
		q.pop();
		for(int i = 0; i < 4; i++)
		{
			ed.x = st.x + xx[i];
			ed.y = st.y + yy[i];
			int p = check(ed.x, ed.y);
			if(p==0) continue;
			if(p==2) return step[st.x][st.y]+1;
			//移动 入队 步数加1 
			q.push(ed);
			step[ed.x][ed.y] = step[st.x][st.y] + 1; 
		}
	}
	return -1;
}

int main(int argc, char *argv[])
{
	while(scanf("%d%d",&N,&M) && (N||M))
	{
		getchar();
		for(int i = 0; i < N; i++)
			gets(map[i]);
		LposX = -1, LposY = -1;
		PlayerNum = 0;
		for(int i = 0; i < N; i++)
		{
			for(int j = 0; j < M; j++)
			{
				if(map[i][j] == 'D')
				{
					DPlayer[PlayerNum].x = i;
					DPlayer[PlayerNum++].y = j;
					if(LposX == -1)
					{
						LposX = i;
						LposY = j;
					}
				}
			} 
		}
		int ans = BFS(LposX,LposY);
		if(ans == -1)
			puts("Impossible");
		else
			printf("%d\n",ans);
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值