XMU C语言程序设计实践(4)

以下实验二选一。

1、使用队列实现迷宫算法,找到最短路径。

2、实现顺序队列和链队列的所有基本操作,InitQueue(&Q);DestroyQueue(&Q);ClearQueue(&Q);QueueEmpty(Q);QueueLength(Q);GetHead(Q, &e); EnQueue(&Q, e);DeQueue(&Q, &e);QueueTraverse(Q, visit())。

 

 

实验1:

 1 //
 2 //by coolxxx
 3 //
 4 #include<stdio.h>
 5 #include<stdlib.h>
 6 #include<string.h>
 7 #define max(a,b) ((a)>(b)?(a):(b))
 8 #define min(a,b) ((a)<(b)?(a):(b))
 9 #define abs(a) ((a)>0?(a):(-(a)))
10 #define sqr(a) ((a)*(a))
11 #define swap(a,b) (a)^=(b),(b)^=(a),(a)^=(b)
12 #define eps 1e-8
13 #define MAX 0x7f7f7f7f
14 #define N 1004
15 #define M 1000004
16 int n,m,ans,lll,cas,cass;
17 int sx,sy,ex,ey;
18 int q[M][2];
19 int fa[M];
20 int u[N][N];
21 char map[N][N];
22 int dx[]={-1,1,0,0};
23 int dy[]={0,0,-1,1};
24 void print(int x)
25 {
26     int i,j;
27     if(q[x][0]==sx && q[x][1]==sy)
28     {
29         printf("(%d,%d)->",sx,sy);
30         return;
31     }
32     print(fa[x]);
33     printf("(%d,%d)->",q[x][0],q[x][1]);
34 }
35 int spfa()
36 {
37     int i,j,x,y,xx,yy,h,t;
38     memset(q,0,sizeof(q));
39     h=0;t=1;
40     q[1][0]=sx;q[1][1]=sy;
41     u[sx][sy]=1;
42     while(h!=t)
43     {
44         x=q[++h][0];y=q[h][1];
45         if(x==ex && y==ey)
46         {
47             print(fa[t]);
48             printf("(%d,%d)\n",ex,ey);
49             return 1;
50         }
51         for(i=0;i<4;i++)
52         {
53             xx=x+dx[i];
54             yy=y+dy[i];
55             if(xx<1 || yy<1 || xx>n || yy>m || map[xx][yy]=='1' || u[xx][yy])continue;
56             q[++t][0]=xx;
57             q[t][1]=yy;
58             fa[t]=h;
59             u[xx][yy]=1;
60         }
61     }
62     return 0;
63 }
64 int main()
65 {
66 //    freopen("1.txt","r",stdin);
67     int i,j;
68     scanf("%d",&n);
69     m=n;sx=1;sy=1;ex=n;ey=m;
70     for(i=1;i<=n;i++)
71     {
72         scanf("%s",map[i]+1);
73         puts(map[i]+1);
74     }
75     if(map[sx][sy]=='1' || map[ex][ey]=='1'){puts("No way");return 0;}
76     if(!spfa())puts("No way");
77     return 0;
78 }
79 /*
80 
81 */
View Code

 

实验2:

 

可参考STL queue

posted @ 2017-06-28 17:34  Cool639zhu  阅读(298)  评论(0编辑  收藏  举报