题目链接
http://acm.fzu.edu.cn/problem.php?pid=2285
题目
洪尼玛今天准备去寻宝,在一个n*n (n行, n列)的迷宫中,存在着一个入口、一些墙壁以及一个宝藏。由于迷宫是四连通的,即在迷宫中的一个位置,只能走到与它直接相邻的其他四个位置(上、下、左、右)。现洪尼玛在迷宫的入口处,问他最少需要走几步才能拿到宝藏?若永远无法拿到宝藏,则输出-1。
Input
多组测试数据。
输入第一行为正整数n,表示迷宫大小。
接下来n行,每行包括n个字符,其中字符’.’表示该位置为空地,字符’#’表示该位置为墙壁,字符’S’表示该位置为入口,字符’E’表示该位置为宝藏,输入数据中只有这四种字符,并且’S’和’E’仅出现一次。
n≤1000
Output
输出拿到宝藏最少需要走的步数,若永远无法拿到宝藏,则输出-1。
Sample Input
5
S.#..
#.#.#
#.#.#
#…E
#….
Sample Output
7
分析
从一点到另一点,两点都唯一。优先队列去找即可。注意优先队列的小于号重载和一般的相反。
AC代码
#include <cstdio>
#include <queue>
#include <cstring>
using namespace std;
const int maxn=1e3+100;
char mp[maxn][maxn];
int si,sj;
int ei,ej;
int n;
int dir[4][2]={0,1,0,-1,1,0,-1,0};
bool vis[maxn][maxn];
struct node
{
int x,y,t;
node(int x,int y,int t)
{
this->x=x;this->y=y;this->t=t;
}
bool operator<(const node &o)const
{
return t>o.t;
}
};
bool valid(int x,int y)
{
return x>=0 && x<n && y>=0 && y<n && mp[x][y]!='#' && !vis[x][y];
}
void bfs()
{
priority_queue<node> que;
que.push(node(si,sj,0));
vis[si][sj]=true;
while(!que.empty())
{
node tmp=que.top();que.pop();
if(tmp.x==ei && tmp.y==ej)
{
printf("%d\n",tmp.t);
return ;
}
for(int i=0;i<4;i++)
{
int fx=tmp.x+dir[i][0],fy=tmp.y+dir[i][1];
if(valid(fx,fy))
{
vis[fx][fy]=true;
que.push(node(fx,fy,tmp.t+1));
}
}
}
printf("%d\n",-1);
return ;
}
int main()
{
while(~scanf("%d",&n))
{
memset(vis,false,sizeof(vis));
for(int i=0;i<n;i++)
scanf("%s",mp[i]);
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
{
if(mp[i][j]=='S') si=i,sj=j;
if(mp[i][j]=='E') ei=i,ej=j;
}
bfs();
}
return 0;
}