BFS 搜索 Problem 1009 连连看
2016-04-21 11:43
435 查看
Problem ID:1009 连连看
简单题意:一个棋盘上放了若干个棋子,如果两个相同(位置不同)的棋子能用一条线连起来,且转折次数不超过2次,则可将其消去。给出棋盘和棋子,以及试图消去的两个棋子位置。如果能消去,输出“YES”,如果不能,输出“NO”。
解题思路形成过程:利用BFS进行搜索,符合要求的下一步共有3个要求:
①:连线必须在棋盘内,不能从外面绕出去;
②:下一个目标区域的没有以任何方向走过,或者新的走法转折次数更少;
③:此区域无棋子(如果找到了目标直接return返回)。
注意:如果选择的两个棋子类型不同,或其中任意一个位置没有棋子,则须直接输出“NO”。
感想: 一个不是太难的题,WA了16次………… 改了N久…… 最后才发现WA的原因是如果是该输出“NO”,主函数里的条件该写成对应的-1 而不是0…… 反复检查居然没有发现…………
还有就是中间有一个情况没有考虑到…
一开始用的DFS,会超时,后来又改成BFS写的。不过如果剪枝处理的比较好,DFS应该也可以。
第一次见识和学习了三维数组,挺好使。
注意条件的整合,以提高代码效率。
无论如何…… 终于是AC了…
代码:
#include<iostream> #include<stdio.h> #include<string.h> #include<queue> using namespace std; #define INF 10000 int cmap[1001][1001]; int mark[1001][1001][4]; int query[4]; int dir[4][2]={{-1,0},{1,0},{0,-1},{0,1}}; int n,m; int BFS() { queue<int>s; s.push(query[0]); //队列中4个元素为一组,分别是当前行(r),当前列(c),当前方向(state),当前转折次数(cnt)。 s.push(query[1]); s.push(-1); s.push(-1); while(!s.empty()) { int r=s.front(); s.pop(); int c=s.front(); s.pop(); int state=s.front(); s.pop(); int cnt=s.front(); s.pop(); for(int i=0;i<4;++i){ //i也代表了移动的方向。i=0,1,2,3分别代表了上,下,左,右。 int t_cnt=cnt; if(i!=state) ++t_cnt; if(t_cnt>2) continue; if(r+dir[i][0]==query[2]&&c+dir[i][1]==query[3]) return 1; if(r+dir[i][0]>=0&&r+dir[i][0]<n&&c+dir[i][1]>=0&&c+dir[i][1]<m) if(mark[r+dir[i][0]][c+dir[i][1]][i]>t_cnt) //没走过或者新的路径转折次数更少 if(cmap[r+dir[i][0]][c+dir[i][1]]==0){ // cout<<r<<' '<<c<<' '<<"go"<<endl; s.push(r+dir[i][0]); s.push(c+dir[i][1]); s.push(i); s.push(t_cnt); mark[r+dir[i][0]][c+dir[i][1]][i]=t_cnt; } } } return -1; } int main() { freopen("1.txt","r",stdin); while(1) { scanf("%d%d",&n,&m); if(n==0) return 0; for(int i=0;i<n;++i) for(int j=0;j<m;++j) cin>>cmap[i][j]; int q; scanf("%d",&q); for(int i=0;i<q;++i){ scanf("%d%d%d%d",&query[0],&query[1],&query[2],&query[3]); --query[0]; --query[1]; --query[2]; --query[3]; memset(mark,INF,sizeof(mark));//INF if(cmap[query[0]][query[1]]!=cmap[query[2]][query[3]]||cmap[query[0]][query[1]]==0||cmap[query[2]][query[3]]==0||(query[0]==query[2]&&query[1]==query[3])) printf("NO\n"); else if(BFS()==1) printf("YES\n"); else if(BFS()==-1) printf("NO\n"); } } }
相关文章推荐
- cocoapods导入第三方类库后头文件没有代码提示
- RGB/YUV/YCbCr--关于显示,颜色你需要了解的一些 事 入门扫盲好文章
- 使用ajaxSubmit异步上传图片并展示
- springmvc结合xheditor实现图文编辑
- 330. Patching Array
- yum源的配置
- android 使用Notification弹多个通知时,点击跳转intent取值时总是最后一个
- C++中类的成员函数作为 pthread_create的线程函数
- Cocoapods多模块开发
- 爬虫链接
- CSMA/CD 机制学习
- C++第4次作业
- JQuery判断form表单是否为空
- JNDI的理解
- 恢复出厂设置全部格式化SD phone Stoarge
- Radware Linkproof版本升级
- android progressBar 自定义 进度颜色
- 70、ExtJs的combobox的监听事件
- ios 解决 dyld: Library not loaded: /System/Library/Frameworks/CoreMedia.framework/CoreMedia
- c++作业4