迷宫问题:hdoj1242--BFS基本应用

#include <iostream>

using namespace std;
const int MAX=205;
char map[MAX][MAX];

int bfs_search(int si,int sj,int di,int dj)
{
	int dir[4][2]={0,1,0,-1,1,0,-1,0};
	int newi,newj;
	typedef struct {
		int i,j,lev;
		int guard;
	}Queue;
	Queue Q[MAX*MAX];
	Queue e;
	int top,rear;
	top=rear=0;
	Q[rear].i=si;Q[rear].j=sj;Q[rear].guard=0;Q[rear].lev=0;
	rear++;
	while(top!=rear)
	{
		e=Q[top++];
		if(e.i==di && e.j==dj)
			return e.lev;
		if(e.guard==1)
		{
			e.guard=0;
			e.lev++;
			Q[rear++]=e;
		}
		else
		{
			for(int k=0;k<4;k++)
			{
				newi=e.i+dir[k][0];
				newj=e.j+dir[k][1];
				if(map[newi][newj]!='#')
				{
					Q[rear].i=newi;
					Q[rear].j=newj;
					Q[rear].lev=e.lev+1;
					if(map[newi][newj]=='x')
						Q[rear].guard=1;
					else
						Q[rear].guard=0;
					map[newi][newj]='#';
					rear++;
				}
			}
		}
	}
	return 0;
}

void main()
{
	int N,M;
	int si,sj,di,dj;
	while(scanf("%d%d",&N,&M)!=EOF)
	{
		int i,j;
		for(i=0;i<=N+1;i++)
			map[i][0]=map[i][M+1]='#';
		for(j=1;j<=M;j++)
			map[0][j]=map[N+1][j]='#';
		for(i=1;i<=N;i++)
		{
			for(j=1;j<=M;j++)
			{
				cin>>map[i][j];
				if(map[i][j]=='a')
				{si=i;sj=j;}
				else if(map[i][j]=='r')
				{di=i;dj=j;}
			}
		}
		int nstep=bfs_search(si,sj,di,dj);
		if(nstep!=0)
			cout<<nstep<<endl;
		else
			cout<<"Poor ANGEL has to stay in the prison all his life."<<endl;
		
	}
}


你可能感兴趣的:(迷宫问题:hdoj1242--BFS基本应用)