洛谷P1746 离开中山路

题目链接:https://www.luogu.com.cn/problem/P1746

也是很浅显的bfs模板题,甚至把我的上一篇关于mzc和男家丁的游戏的代码拿过来稍作修改就可以AC;

需要注意的是,在输入中输入的不是整形数组,而是字符型数组,否则输入会出错,这一点需要注意;

参考代码如下:

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 int n;
 4 int sx,sy,fx,fy;
 5 int dis[1010][1010];
 6 char a[1010][1010];
 7 bool vis[1010][1010];
 8 struct node
 9 {
10     int x;
11     int y;
12 };
13 int ans;
14 int dx[4]={-1,0,1,0};
15 int dy[4]={0,-1,0,1};
16 int bfs(int bx,int by)
17 {
18     vis[bx][by]=true;
19     queue<node>q;
20     node start,next;
21     start.x=bx;
22     start.y=by;
23     q.push(start);
24     while(!q.empty())
25     {
26         start=q.front();;
27         q.pop();
28         if(start.x==fx&&start.y==fy)
29         return dis[start.x][start.y];
30         for(register int i=0;i<4;i++)
31         {
32             next.x=start.x+dx[i];
33             next.y=start.y+dy[i];
34             if(next.x<=0||next.x>n||next.y<=0||next.y>n)
35             continue;
36             if(vis[next.x][next.y]==true||a[next.x][next.y]=='1')
37             continue;
38             dis[next.x][next.y]=dis[start.x][start.y]+1;
39             vis[next.x][next.y]=true;
40             q.push(next);
41         }
42     }
43     return -1;
44 }
45 int main()
46 {
47     ios::sync_with_stdio(false);
48     cin>>n;
49     for(register int i=1;i<=n;i++)
50     {
51         for(register int j=1;j<=n;j++)
52         {
53             cin>>a[i][j];
54         }
55     }
56     cin>>sx>>sy>>fx>>fy;
57     ans=bfs(sx,sy);
58     cout<<ans<<endl;
59     return 0;
60 }

 

posted @ 2022-03-18 17:58  江上舟摇  阅读(52)  评论(0编辑  收藏  举报