HDU 1242 Rescue (BFS+優先隊列)

鏈接:http://acm.hdu.edu.cn/showproblem.php?pid=1242

angel被困在迷宮裏,他的朋友們去救。n*m的迷宮,'.'代表路,'#'代表牆,'x'代表守衛,'r'代表朋友,'a'代表ANGEL。求最少時間。由於該題目僅含有一個a點,但是可以含有多個r點,所以從a點開始搜,這點很容易想到。可是寫了很久一直Wa,Wa的莫名其妙的感覺,然後看了些題解,說是優先隊列,在此之前,應該是沒有做過優先隊列,這是我的第一道,然後連重載都不會的我去看了優先隊列這部分。因爲當步數相同時時間不一定是最小的,所以要進行處理,這時候優先隊列的優勢就出來了,也確實,很容易就Ac了,不過好像好多人沒用優先隊列也過了。

代碼:

#include<cstdio>
#include<iostream>
#include<queue>

using namespace std;

char map[205][205];
int n,m;
int dir[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
int si,sj;

struct point
{
	int x,y,time;
	
	friend bool operator < (point a, point b)
	{
		return a.time>b.time;  //時間少的先出隊
	}
} start;

int BFS(int a,int b)
{
	start.x=a;
	start.y=b;
	start.time=0;

	priority_queue<point> q;
	point cur,next;
    int i;

	q.push(start);

	while(!q.empty())
	{

		cur=q.top(); //取出隊首元素
		q.pop();

		for(i=0;i<4;i++)
		{
			next.x=cur.x+dir[i][0];
			next.y=cur.y+dir[i][1];
			next.time=cur.time+1;

			if(next.x>=0&&next.x<n&&next.y>=0&&next.y<m)
				if(map[next.x][next.y]!='#')
				{
		 
					if(map[next.x][next.y]=='x')
						next.time++;
					
					if(map[next.x][next.y]=='r')
						return next.time;

					map[next.x][next.y]='#';

					q.push(next);
				}
		}
		
	}

return -1;
}

int main()
{
	
	while(scanf("%d%d",&n,&m)!=EOF)
	{
		getchar();
		for(int i=0;i<n;i++)
		{
			for(int j=0;j<m;j++)
			{
			  scanf("%c",&map[i][j]);

			  if(map[i][j]=='a')
			  {
				  si=i;
				   sj=j;
			  }
			}
			getchar();
		}

		int count=BFS(si,sj);
		if(count>=0)
			printf("%d\n",count);
		else
			printf("Poor ANGEL has to stay in the prison all his life.\n");
	}

	return 0;

}
			
		
/*
5 4
####
#xa.
#x#.
#x#.
#r..
*/
	

   


 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章