Qiuqiqiu  
不管道路多么崎岖坎坷,我永远不停下追逐梦想的脚步!

http://acm.hdu.edu.cn/showproblem.php?pid=2757

BFS+优先队列

我的代码
 1 #include <cstdio>
2 #include <cstring>
3 #include <queue>
4 using namespace std;
5 const int N=1010,INF=10000;
6 struct sta
7 {
8 int x,y,d;
9 };
10 struct qcmp
11 {
12 bool operator() (const sta a,const sta b)
13 {
14 return a.d>b.d;
15 }
16 };
17 priority_queue<sta,vector<sta>,qcmp> q;
18 const int dx[8]={-1,-1,0,1,1,1,0,-1},dy[8]={0,1,1,1,0,-1,-1,-1};
19 char maze[N][N];
20 int dist[N][N];
21 int n,m;
22 int bfs(int x,int y,int ex,int ey)
23 {
24 if (x==ex && y==ey) return 0;
25 while (!q.empty()) q.pop();
26 int d,nx,ny;
27 dist[x][y]=0;
28 sta u={x,y,0},v; q.push(u);
29 while (!q.empty())
30 {
31 u=q.top(); q.pop();
32 x=u.x; y=u.y;
33 if (x==ex && y==ey) return dist[x][y];
34 for (d=0;d<8;d++)
35 {
36 nx=x+dx[d]; ny=y+dy[d];
37 if (0<nx && nx<=n && 0<ny && ny<=m && dist[nx][ny]>dist[x][y]+(d!=maze[x][y]-'0'))
38 {
39 dist[nx][ny]=dist[x][y]+(d!=maze[x][y]-'0');
40 v.x=nx; v.y=ny; v.d=dist[nx][ny];
41 q.push(v);
42 }
43 }
44 }
45 }
46 int main()
47 {
48 int i,j,t,x,y,ex,ey;
49 while (scanf("%d%d",&n,&m)!=EOF)
50 {
51 for (i=1;i<=n;i++) scanf("%s",maze[i]+1);
52 scanf("%d",&t);
53 while (t--)
54 {
55 for (i=1;i<=n;i++) for (j=1;j<=n;j++) dist[i][j]=INF;
56 scanf("%d%d%d%d",&x,&y,&ex,&ey);
57 printf("%d\n",bfs(x,y,ex,ey));
58 }
59 }
60 }

 

posted on 2011-12-07 15:18  Qiuqiqiu  阅读(251)  评论(0编辑  收藏  举报