您的位置:首页 > 其它

HDU 2757 Ocean Currents

2011-12-07 15:18 330 查看
http://acm.hdu.edu.cn/showproblem.php?pid=2757

BFS+优先队列

我的代码

#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
const int N=1010,INF=10000;
struct sta
{
int x,y,d;
};
struct qcmp
{
bool operator() (const sta a,const sta b)
{
return a.d>b.d;
}
};
priority_queue<sta,vector<sta>,qcmp> q;
const int dx[8]={-1,-1,0,1,1,1,0,-1},dy[8]={0,1,1,1,0,-1,-1,-1};
char maze

;
int dist

;
int n,m;
int bfs(int x,int y,int ex,int ey)
{
if (x==ex && y==ey) return 0;
while (!q.empty()) q.pop();
int d,nx,ny;
dist[x][y]=0;
sta u={x,y,0},v; q.push(u);
while (!q.empty())
{
u=q.top(); q.pop();
x=u.x; y=u.y;
if (x==ex && y==ey) return dist[x][y];
for (d=0;d<8;d++)
{
nx=x+dx[d]; ny=y+dy[d];
if (0<nx && nx<=n && 0<ny && ny<=m && dist[nx][ny]>dist[x][y]+(d!=maze[x][y]-'0'))
{
dist[nx][ny]=dist[x][y]+(d!=maze[x][y]-'0');
v.x=nx; v.y=ny; v.d=dist[nx][ny];
q.push(v);
}
}
}
}
int main()
{
int i,j,t,x,y,ex,ey;
while (scanf("%d%d",&n,&m)!=EOF)
{
for (i=1;i<=n;i++) scanf("%s",maze[i]+1);
scanf("%d",&t);
while (t--)
{
for (i=1;i<=n;i++) for (j=1;j<=n;j++) dist[i][j]=INF;
scanf("%d%d%d%d",&x,&y,&ex,&ey);
printf("%d\n",bfs(x,y,ex,ey));
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: