洛谷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 }
本文来自博客园,作者:江上舟摇,转载请注明原文链接:https://www.cnblogs.com/LQS-blog/p/16022953.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】