2727:仙岛求药

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<queue>
 4 #include<cstring>
 5 using namespace std;
 6 const int N=21;
 7 struct node{
 8     int x,y,step;
 9 }now,nxt;
10 queue<node>q;
11 int n,m;
12 int a[N][N];
13 int xd[4]={-1,0,1,0};
14 int yd[4]={0,1,0,-1};
15 bool vis[N][N];
16 int sx,sy,ex,ey;
17 void bfs()
18 {
19     if(sx==ex&&sy==ey)
20     {
21       cout<<"0"<<endl;
22       return ;
23     }
24     while(!q.empty())q.pop();
25     now.x=sx;now.y=sy;now.step=0;
26     vis[sx][sy]=true;
27     q.push(now);
28     while(!q.empty())
29      {
30          now=q.front();q.pop();
31          for(int i=0;i<4;i++)
32           {
33               int xx=now.x+xd[i];
34               int yy=now.y+yd[i];
35               if(xx>=1&&xx<=n&&yy>=1&&yy<=m&&!vis[xx][yy]&&a[xx][yy])
36                {
37                    if(xx==ex&&yy==ey)
38                     {
39                         cout<<now.step+1<<endl;
40                         return ;
41                     }
42                  nxt.x=xx;
43                  nxt.y=yy;
44                  nxt.step=now.step+1;
45                  vis[nxt.x][nxt.y]=true;
46                  q.push(nxt);
47                }
48          } 
49      }
50      printf("-1\n");
51 }
52 int main()
53 {
54     while(scanf("%d%d",&n,&m)!=EOF)
55     {    
56         if(!n) return 0;
57         memset(vis,0,sizeof(vis));
58         memset(a,0,sizeof(a));
59      for(int i=1;i<=n;i++) 
60         for(int j=1;j<=m;j++)
61          {
62              char ch;
63              cin>>ch;
64                if(ch=='#') continue;
65                a[i][j]=1;
66                if(ch=='@')  {  ex=i; ey=j;}
67              else if(ch=='*') { sx=i; sy=j;}
68          } 
69      bfs();    
70     } 
71 }

 

posted @ 2017-04-24 20:19  ioioioioioio  阅读(149)  评论(0编辑  收藏  举报