POJ 1753 FLIP GAME——枚举深度的dfs
2014-07-24 15:59
513 查看
题目链接点击打开链接
题意:将白块翻成黑块或者将黑块翻成白块,在每一次反转时相邻4个也会翻转,问最少需要翻转多少次使得棋盘上的棋子清一色。
思路:这是一道搜索题,对于每个棋子,翻或不翻。一共有2^16种情况。最多需要翻转16步,面对一道看似没有深度的树进行搜索,要找到最少的步数,只需枚举0—16的深度即可。这种方法在刘汝佳白书中有提到。但是我看书不精,后来是看了网上解题报告,才意识到这种方法的。
AC代码
题意:将白块翻成黑块或者将黑块翻成白块,在每一次反转时相邻4个也会翻转,问最少需要翻转多少次使得棋盘上的棋子清一色。
思路:这是一道搜索题,对于每个棋子,翻或不翻。一共有2^16种情况。最多需要翻转16步,面对一道看似没有深度的树进行搜索,要找到最少的步数,只需枚举0—16的深度即可。这种方法在刘汝佳白书中有提到。但是我看书不精,后来是看了网上解题报告,才意识到这种方法的。
AC代码
#include<iostream> #include<cstdio> #include<string> #include<cstring> #include<iomanip> #include<algorithm> #include<cmath> using namespace std; int step,flag; bool a[5][5]; int dir[5][2]= {{1,0},{-1,0},{0,1},{0,-1},{0,0}}; bool judge()//判断同色 { int i,j; for(i=0; i<4; i++) { for(j=0; j<4; j++) if(a[i][j]!=a[0][0]) return false; } return true; } void flip(int x,int y)//翻翻~~~ { for(int i=0; i<5; i++) { int tmpx=x+dir[i][0]; int tmpy=y+dir[i][1]; if(tmpx>=0 && tmpx<4 && tmpy>=0 && tmpx<4) { a[tmpx][tmpy]=!a[tmpx][tmpy]; } } } void dfs(int x,int y,int cnt) { if(cnt==step) { flag=judge(); return ; } if(flag || y==4 ) return; flip(x,y); if(x+1<4) dfs(x+1,y,cnt+1); else dfs(0,y+1,cnt+1); if(!flag) { flip(x,y); if(x+1<4) dfs(x+1,y,cnt); else dfs(0,y+1,cnt); } } int main() { int i,j; memset(a,0,sizeof(a)); flag=0; char tmp; for(i=0; i<4; i++) { for(j=0; j<4; j++) { cin>>tmp; if(tmp=='b') a[i][j]=true; } } for(step=0; step<=16; step++) { dfs(0,0,0); if(flag) { cout<<step<<endl; break; } } if(!flag) cout<<"Impossible\n"; return 0; }
相关文章推荐
- 文章标题 POJ 1753 : Flip Game(枚举+dfs)
- poj 1753 : Flip Game (枚举+dfs)
- poj 1753 Flip Game——DFS(分类是枚举)
- poj 1753 : Flip Game (枚举+dfs)
- POJ 1753 Flip Game 暴力搜索(dfs加枚举)
- 1753 poj Flip Game 据说是枚举,我这种DFS算是枚举不?
- poj Flip Game(DFS)(枚举)
- (枚举初级+回溯)poj1753 Flip Game
- POJ1753 Flip Game(搜索,枚举,位运算压缩)
- poj Flip Game(DFS)(枚举)
- DFS.枚舉::poj1753 flip game && poj2965 the Pilots Brothers'refrigerator
- POJ-1753 Flip Game【暴力枚举】
- poJ 1753(dfs) Flip Game
- poj Flip Game(DFS)(枚举)
- poj Flip Game(DFS)(枚举)
- poj Flip Game(DFS)(枚举)
- poj dfs相关之1753 Flip Game
- poj Flip Game(DFS)(枚举)
- poj Flip Game(DFS)(枚举)
- poj Flip Game(DFS)(枚举)