广度优先搜索--迷宫

核心:队列

 1 #include<stdio.h>
 2 struct note
 3 {
 4     int x;
 5     int y;
 6     int s;
 7     
 8 };
 9 int main(){
10     struct note que[2501];
11     int a[51][51]={0},book[51][51]={0};
12     int next[4][2]={{0,1},{1,0},{0,-1},{-1,0}};
13     int head,tail;
14     int i,j,k,n,m,startx,starty,p,q,tx,ty,flag;
15     
16     scanf("%d %d",&n,&m);
17     for(i=1;i<=n;i++)
18         for(j=1;j<=m;j++)
19             scanf("%d",&a[i][j]);
20     scanf("%d %d %d %d",&startx,&starty,&p,&q);
21     head=1;tail=1;
22     que[tail].x=startx;
23     que[tail].y=starty;
24     que[tail].s=0;
25     tail++;
26     book[startx][starty]=1;
27     flag=0;
28     
29     while(head<tail){
30         for(k=0;k<=3;k++){
31             tx=que[head].x+next[k][0];
32             ty=que[head].y+next[k][1];
33             if(tx<1||tx>n||ty<1||ty>m)
34                 continue;
35             if(a[tx][ty]==0&&book[tx][ty]==0){
36             book[tx][ty]=1;
37             que[tail].x=tx;
38             que[tail].y=ty;
39             que[tail].s=que[head
40             ].s+1;
41             tail++;
42             }
43             if(tx==p&&ty==q){
44                 flag=1;
45                 break;
46             }
47         }
48             if(flag==1)break;
49             head++;    
50     }
51     printf("%d",que[tail-1].s);    
52 }

 

posted @ 2022-04-05 00:19  HzzzzLi  阅读(24)  评论(0)    收藏  举报