HDU 1242 RESCUE(BFS)

BFS,注意把步数和时间区分对待

第一次写BFS代码微乱。

#include<stdio.h>
#define inf 100000000

char map[210][210];
int mintime[210][210];
int n,m,res;
char c;
int si,sj,ei,ej;
int xx[4]={0,0,1,-1};
int yy[4]={1,-1,0,0};
int ti,tj,tbu,ttime;

int queue[40010][4];		//0:i	1:j	2:bushu	3:time;

int inarea(int x,int y)
{
	return x>=0 && y>=0 && x<n && y<m;
}

int bfs(int x,int y,int bu,int time)
{
	int head=0,tail=0;
	queue[tail][0]=x;
	queue[tail][1]=y;
	queue[tail][2]=bu;
	queue[tail][3]=time;
	tail++;
	while(head<tail)
	{
		for(int i=0;i<4;i++)
		{
			ti=queue[head][0]+xx[i];
			tj=queue[head][1]+yy[i];
			if(inarea(ti,tj) && map[ti][tj]!='#')
			{
				tbu=queue[head][2]+1;
				ttime=queue[head][3]+1;
				if(map[ti][tj]=='x') ttime++;
				if(ttime<mintime[ti][tj])
				{
					mintime[ti][tj]=ttime;
					queue[tail][0]=ti;
					queue[tail][1]=tj;
					queue[tail][2]=tbu;
					queue[tail][3]=ttime;
					tail++;
				}
			}
		}
		head++;
	}
	return mintime[ei][ej];
}

int main()
{
	while(~scanf("%d%d",&n,&m))
	{
		getchar();
		for (int i=0; i<n; i++)
		{
			for (int j=0; j<m; j++)
			{
				c=getchar();
				mintime[i][j]=inf;
				if(c=='r'){si=i; sj=j; map[i][j]='.';}
				else if(c=='a'){ei=i; ej=j; map[i][j]='.';}
				else map[i][j]=c;
			}
			getchar();
		}
		res=bfs(si,sj,0,0);
		if(res==inf) printf("Poor ANGEL has to stay in the prison all his life.\n");
		else printf("%d\n",res);
	}
}
posted @ 2011-06-11 17:39  谁也打不过  阅读(152)  评论(0编辑  收藏  举报