洛谷 P1141 01迷宫
来源:互联网 发布:java错误找不到符号 编辑:程序博客网 时间:2024/05/16 04:33
洛谷 P1141 01迷宫
题目分析:看网上的大佬们都说这道题普通的搜索和广搜都过不去,得要优化一下,有些大佬使用hash判重和并查集?(我是没有懂,我还是太菜了)然后就继续翻别人的博客,后面发现了两种很优美的算法,一种是深搜,一种是广搜。分别贴出来吧,其实这两位的都用到了差不多一样的优化,这种优化挺好的。(不要问我为什么都是贴的别人的,因为考试快来了,没那多时间了,所以主要是学学思路)
深搜代码(来自洛谷用户:囧人232)
#include<iostream>#include<cstdio>#include<cstring>#include<algorithm>using namespace std;const int dx[4]={-1,0,1,0};const int dy[4]={0,1,0,-1};int g[1001][1001],f[1001][1001],d[1000005];//d数组就是在下的优化,每种颜色对应的答案int n,m,k,ans,cnt=1;string c;void init(){ans=0;}void dfs(int x,int y){ ans++; f[x][y]=cnt; for(int i=0;i<4;++i) { int xx=x+dx[i],yy=y+dy[i]; if(!f[xx][yy]&&1<=xx&&xx<=n&&1<=yy&&yy<=m&&(g[xx][yy]!=g[x][y])) dfs(xx,yy); } d[cnt]=ans;}int main(){ scanf("%d%d",&n,&k); for(int i=1;i<=n;i++){ cin>>c; m=c.size(); for(int j=0;j<m;j++) g[i][j+1]=c[j]-'0'; } for(int i=1;i<=k;i++){ init(); int a,b; scanf("%d%d",&a,&b); if(!f[a][b]){ dfs(a,b); cnt++; } printf("%d\n",d[f[a][b]]); } return 0;}
下面这种是广搜(Luogu P1141 01迷宫)
#include <cstdio>using namespace std;struct node { int x,y,s;}a[1000001];char map[1001][1001];int n,m,startx,starty,num,book[1001][1001],mark[1001][1001],ans[1000001]; int next[4][2]={{0,1},{1,0},{0,-1},{-1,0}};int bfs(int color){ int head=1,tail=2,tx,ty,k,sum=1; mark[startx][starty]=color; book[startx][starty]=1; a[head].x=startx;a[head].y=starty; a[head].s=0; while(head<tail){ for(k=0;k<=4-1;k++){ tx=a[head].x+next[k][0]; ty=a[head].y+next[k][1]; if(tx<1 || tx>n || ty<1 || ty>n) continue; if(map[tx][ty]!=map[a[head].x][a[head].y] && book[tx][ty]==0){ book[tx][ty]=1; mark[tx][ty]=color; sum++; a[tail].x=tx; a[tail].y=ty; a[tail].s=a[head].s+1; tail++; } } head++; } return sum;}int main(){ num=1; int i,j; scanf("%d %d\n",&n,&m); for(i=1;i<=n;i++){ gets(map[i]+1); } for(i=1;i<=m;i++) { scanf("%d %d",&startx,&starty); if(mark[startx][starty]!=0) { printf("%d\n",ans[mark[startx][starty]]); } else { ans[num]=bfs(num); printf("%d\n",ans[num]); } num++; } return 0;}
阅读全文
0 0
- 洛谷P1141 01迷宫
- 洛谷P1141 01迷宫
- 洛谷 P1141 01迷宫
- 洛谷P1141 01迷宫
- 洛谷P1141 01迷宫
- 洛谷 P1141 01迷宫
- |洛谷|BFS|P1141 01迷宫
- 【搜索】洛谷 P1141 01迷宫
- 洛谷P1141 01迷宫 解题报告
- P1141 01迷宫题解
- P1141 01迷宫
- P1141 01迷宫
- P1141 01迷宫
- P1141 01迷宫
- Luogu P1141 01迷宫
- 【p1141-01迷宫】解题记录
- [luogu]P1141 01迷宫-宽搜
- (洛谷)【P1141】01迷宫 [广度搜索][高性能]
- SymPy解方程
- C# 开源框架(整理)
- 在 Linux 下安装 NodeJS
- Android Studio工程引用第三方so文件
- Perl-环境搭建
- 洛谷 P1141 01迷宫
- Linux redhat7 udev配置
- python处理url转码的爬虫脚本示例(只供参考)
- iOS开发之界面间传值
- 最简单的视音频播放示例3:Direct3D播放YUV,RGB(通过Surface)
- for循环的优化
- android框架——MVVM
- A child container failed during start
- opencv_Drawing Functions