NYOJ 58-最少步数 DFS或者BFS
发布日期:2021-06-21 03:12:42
浏览次数:24
分类:技术文章
本文共 2099 字,大约阅读时间需要 6 分钟。
DFS+记忆化搜索
/*
qq:1239198605 ctgu_yyf */ #include<iostream> #include<cstdio> #include<string> #include<vector> #include<queue> #include<stack> #include<cstring> #include<algorithm> #include<cmath> const int INF=10001; using namespace std; int mapp[9][9]={ 1,1,1,1,1,1,1,1,1, 1,0,0,1,0,0,1,0,1, 1,0,0,1,1,0,0,0,1, 1,0,1,0,1,1,0,1,1, 1,0,0,0,0,1,0,0,1, 1,1,0,1,0,1,0,0,1, 1,1,0,1,0,1,0,0,1, 1,1,0,1,0,0,0,0,1, 1,1,1,1,1,1,1,1,1, }; int vis[9][9]; int dp[9][9]; int xx[4]={0,1,0,-1}; int yy[4]={1,0,-1,0}; bool inmap(int x,int y) { if(x>=0&&x<=8&&y>=0&&y<=8) return true; return false; } int dfs(int sx,int sy,int ex,int ey) { int nx,ny; if(dp[sx][sy]!=INF) { return dp[sx][sy]; } if(sx==ex&&sy==ey) return 0; for(int i=0;i<4;i++) { nx=sx+xx[i]; ny=sy+yy[i]; if(inmap(nx,ny)&&vis[nx][ny]==0&&mapp[nx][ny]==0) { vis[nx][ny]=1; dp[sx][sy]=min((1+dfs(nx,ny,ex,ey)),dp[sx][sy]); vis[nx][ny]=0; } } return dp[sx][sy]; } int main() { int t; cin>>t; while(t--) { int sx,sy,ex,ey; for(int i=0;i<9;i++) for(int j=0;j<9;j++) { dp[i][j]=INF; } memset(vis,0,sizeof(vis)); cin>>sx>>sy>>ex>>ey; vis[sx][sy]=1; cout<<dfs(sx,sy,ex,ey)<<endl; } return 0;}
BFS
#include<stdio.h>
#include<queue> #include<string.h> #include<algorithm> const int N = 9; bool vis[N][N]; int map[N][N]= { 1,1,1,1,1,1,1,1,1, 1,0,0,1,0,0,1,0,1, 1,0,0,1,1,0,0,0,1, 1,0,1,0,1,1,0,1,1, 1,0,0,0,0,1,0,0,1, 1,1,0,1,0,1,0,0,1, 1,1,0,1,0,1,0,0,1, 1,1,0,1,0,0,0,0,1, 1,1,1,1,1,1,1,1,1, }; using namespace std; int px[4]= {1,-1,0,0}; int py[4]= {0,0,1,-1}; int x,y,ex,ey; struct note{ int x,y; int step; }; int bfs(){ note s; s.x=x,s.y=y,s.step=0; vis[x][y]=true; queue<note>que; que.push(s); while(!que.empty()){ note now=que.front(); que.pop(); if(now.x==ex&&now.y==ey){ return now.step; } for(int l=0;l<4;l++){ note end; end.x=now.x+px[l]; end.y=now.y+py[l]; end.step=now.step; if(vis[end.x][end.y]==false&&map[end.x][end.y]==0){ vis[end.x][end.y]=true; end.step+=1; que.push(end); } } } } int main() { int T; scanf("%d",&T); while(T--){ memset(vis,false,sizeof(vis)); scanf("%d%d%d%d",&x,&y,&ex,&ey); int ans=bfs(); printf("%d\n",ans); } return 0; }转载地址:https://blog.csdn.net/k_koris/article/details/80314595 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
初次前来,多多关照!
[***.217.46.12]2025年01月09日 20时52分21秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
【转】github如何删除一个仓库
2019-06-23
Linux系统编程——进程调度浅析
2019-06-23
大数据Lambda架构
2019-06-23
openCV_java 图像二值化
2019-06-23
状态模式
2019-06-23
DJANGO变动库的一次真实手动经历
2019-06-23
8个基本的引导工具的网页设计师
2019-06-23
【下载分】C语言for循环语句PK自我活动
2019-06-23
VC++获得微秒级时间的方法与技巧探讨(转)
2019-06-23
HDOJ-1010 Tempter of the Bone
2019-06-23
MySQL my.cnf参数配置优化详解
2019-06-23
HDU/HDOJ 2102 A计划 广度优先搜索BFS
2019-06-23
JavaNIO基础02-缓存区基础
2019-06-23
阿里 Blink 正式开源,重要优化点解读
2019-06-23
日本开设无人机专业,打造无人机“人才市场”
2019-06-23
190行代码实现mvvm模式
2019-06-23
PXE部署实例
2019-06-23
cobbler初探------实现自动安装centos6.4
2019-06-23
Android Studio 2.0 preview3 BUG
2019-06-23