Poj 3626 BFS

 

 1 #include <math.h>
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <string.h>
5 #include <memory.h>
6
7 int mat[1010][1010];
8 int i, nNum, tx, ty, ai, bi;
9 int dx[] = {-1, 1, 0, 0};
10 int dy[] = {0, 0, -1, 1};
11
12 struct path
13 {
14 int x, y, step;
15 }q[1000010]={0};
16
17 int IsInBound(int x, int y)
18 {
19 if (x<0 || y<0|| x>1000 || y>1000)
20 {
21 return 0;
22 }
23
24 return 1;
25 }/* IsInBound */
26
27 void BFS()
28 {
29 int rear = -1;
30 int k, front = -1;
31 struct path cur, next;
32
33 cur.x = 500;
34 cur.y = 500;
35 cur.step = 0;
36 q[++rear] = cur;
37
38 mat[500][500] = 1;
39 while (front < rear)
40 {
41 cur = q[++front];
42 if (cur.x==500-ty && cur.y==500+tx)
43 {
44 printf("%d\n", cur.step);
45 break;
46 }/* End of If */
47
48 for (k=0; k<4; ++k)
49 {
50 next.x = cur.x + dx[k];
51 next.y = cur.y + dy[k];
52 if (IsInBound(next.x, next.y) && mat[next.x][next.y]==0)
53 {
54 mat[next.x][next.y] = 1;
55 next.step = cur.step + 1;
56 q[++rear] = next;
57 }
58 }/* End of For */
59 }/* End of WHile */
60 }/* BFS */
61
62 int main()
63 {
64 while (3 == scanf("%d %d %d", &tx, &ty, &nNum))
65 {
66 memset(mat, 0, sizeof(mat));
67 for (i=0; i<nNum; ++i)
68 {
69 scanf("%d %d", &ai, &bi);
70 mat[500-bi][500+ai] = 1;
71 }/* End of For */
72
73 BFS();
74 }/* End of While */
75
76 return 0;
77 }

 

posted @ 2012-08-09 14:55  Maxwell:My Blog  阅读(327)  评论(0编辑  收藏  举报