POJ 3984
来源:互联网 发布:linux ping不通网关 编辑:程序博客网 时间:2024/06/14 03:04
DFS加回溯吧。自己不会回溯,所以这题就没那么简单了、、、
还是借鉴了大神的代码,在这记下来。
这题用回溯把要输出的点保存在栈里,先把没访问过的点放入栈,然后判断是不是到达终点。下面就是判断右边的点和下边的点是否符合要求,符合就DFS,不符合就回溯回到上一个岔路口,并且把不符合的点在栈中删除。
边界处理初始化为1,之前发生过RE,原因是5*5的迷宫加上边界6*6,我只开了6*6,所以RE了。
#include <iostream>#include <cstring>#include <algorithm>#include <vector>#include <stack>#include <cstdio>using namespace std;int arr[7][7];int visit[7][7];typedef pair<int,int> P;stack<P> sk;P p;void dfs(int a,int b){ if(!visit[a][b]) { p.first=a; p.second=b; sk.push(p); visit[a][b]=!visit[a][b]; } if(a==5 && b==5) return ; if(!visit[a][b+1] && !arr[a][b+1]) { dfs(a,b+1); } else if(!visit[a+1][b] && !arr[a+1][b]) { dfs(a+1,b); } else { p.first=sk.top().first; p.second=sk.top().second; sk.pop(); dfs(p.first,p.second); }}int main(){ for(int i=0;i<=6;i++) { arr[i][0]=1; arr[i][6]=1; arr[0][i]=1; arr[6][i]=1; }for(int i=1;i<=5;i++) for(int j=1;j<=5;j++) scanf("%d",&arr[i][j]); memset(visit,0,sizeof(visit)); dfs(1,1); vector<P> v; while(!sk.empty()) { p=sk.top(); v.push_back(p); sk.pop(); } for(int i=v.size()-1;i>=0;i--) printf("(%d, %d)\n",v[i].first-1,v[i].second-1);return 0;}
PS:用结构体代替pair更方便。
0 0
- 【POJ】:POJ 3984
- poj 3984
- poj 3984
- POJ 3984
- POJ 3984
- poj 3984
- poj 3984
- POJ 3984
- poj 3984
- poj 3984
- poj 3984
- poj 3984
- poj 3984
- POJ - 3984
- poj 3984
- poj 3984
- POJ 3984
- poj 3984
- DeepFashion: Powering Robust Clothes Recognition and Retrieval with Rich Annotations – CVPR 2016
- 抽象类和接口联系与区别
- Eclipse中tomcat service设置
- ue4常用方法与技巧汇总
- 离散基础 (3). 差分(微分)的理解和应用
- POJ 3984
- git,svn,github,码云之间联系区别
- EGL workflow
- C++约瑟夫环改良版
- eclipse报错:The project: XXXX which is referenced by the classpath, does not exist.
- XZ_iOS之性能优化——图片文件优化
- 2001年分区联赛普级组之四 装箱问题
- Zabbix-3.2.3实现微信(WeChat)告警
- java中this的用法(1)