题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2822
题目意思:给定起点和终点,问至少需要几步可以从起点到达终点。走X花费0步,走.花费1步。
题目分析:BFS+优先队列。一开始自己敲BFS,WA了,果断模板套起来,果断AC
下面是AC代码:
#include<iostream>
#include<queue>
#include<cstring>
#include<cstdio>
using namespace std;
const int maxn=1005;
char Map[maxn][maxn];
bool vis[maxn][maxn];
struct node
{
int x,y;
int s;
bool friend operator < (node a,node b)
{
return a.s>b.s;
}
};
int n,m,sx,sy,ex,ey;
int dir[][2]={ {0,1},{-1,0},{0,-1},{1,0},{-1,1},{-1,-1},{1,-1},{1,1}};
// 右 上 左 下 右上 左上 左下 右下
//int dir[][2]={{-1,2},{-2,1},{-2,-1},{-1,-2},{1,-2},{2,-1},{2,1},{1,2}};
//马走日的8个方向
int bfs()
{
priority_queue<node>q;
node now,t;
now.x=sx,now.y=sy,now.s=0;
q.push(now);
memset(vis,0,sizeof(vis));
vis[sx][sy]=1;
while(q.size())
{
now=q.top();q.pop();
if(now.x==ex&&now.y==ey) return now.s;
for(int i=0;i<4;i++)
{
t=now;
t.x+=dir[i][0],t.y+=dir[i][1];
if(1<=t.x&&t.x<=n&&1<=t.y&&t.y<=m&&!vis[t.x][t.y])
{
vis[t.x][t.y]=1;
if(Map[t.x][t.y]=='.') t.s++;
q.push(t);
}
}
}
return -1;
}
int main()
{
while(~scanf("%d%d",&n,&m)&&n+m)
{
for(int i=1;i<=n;i++) scanf("%s",Map[i]+1);
//sx=0;sy=0;ex=n-1;ey=m-1;
scanf("%d%d%d%d",&sx,&sy,&ex,&ey);
printf("%d\n",bfs());
}
return 0;
}