dfs+枚举,flip游戏的拓展POJ2965
作者:互联网
POJ 2965 The Pilots Brothers' refrigerator
Description
The game “The Pilots Brothers: following the stripy elephant” has a quest where a player needs to open a refrigerator.
There are 16 handles on the refrigerator door. Every handle can be in one of two states: open or closed. The refrigerator is open only when all handles are open. The handles are represented as a matrix 4х4. You can change the state of a handle in any location [i, j] (1 ≤ i, j ≤ 4). However, this also changes states of all handles in row i and all handles in column j.
The task is to determine the minimum number of handle switching necessary to open the refrigerator.
Input
The input contains four lines. Each of the four lines contains four characters describing the initial state of appropriate handles. A symbol “+” means that the handle is in closed state, whereas the symbol “−” means “open”. At least one of the handles is initially closed.
Output
The first line of the input contains N – the minimum number of switching. The rest N lines describe switching sequence. Each of the lines contains a row number and a column number of the matrix separated by one or more spaces. If there are several solutions, you may give any one of them.
Sample Input
-+-- ---- ---- -+--
Sample Output
6 1 1 1 3 1 4 4 1 4 3 4 4
代码是看过网上大佬题解的,因为不知道怎么记录路径...
#include <stdio.h> #include <string> #include <string.h> #include <iostream> #include <algorithm> #include <cmath> using namespace std; const int inf=0x3f3f3f; int ans,flag; int map[10][10]; struct node{ int p,q; }a[18]; int judge(){ for(int i=1;i<=4;++i){ for(int j=1;j<=4;++j){ if(map[i][j]==0){ return 0; } } } return 1; } void swap(int x,int y){ map[x][y]=!map[x][y]; for(int i=1;i<=4;++i) { map[x][i]=!map[x][i]; map[i][y]=!map[i][y]; //翻过来 } } void dfs(int x,int y,int step){ if(step==ans) { flag=judge(); //判断是否全翻完; return; } if(flag||x>=5) { return; // 判断是否走完或者翻完 } swap(x,y); if(y<4){ dfs(x,y+1,step+1); a[step].p=x;//记录路径 a[step].q=y; } //全部16枚举一遍; else{ dfs(x+1,1,step+1);//换行翻 a[step].p=x; a[step].q=y; } swap(x,y); if(y<4) { dfs(x,y+1,step); } else { dfs(x+1,1,step); } } int main(void){ char b; for(int i=1;i<=4;++i){ for(int j=1;j<=4;++j){ scanf("%c",&b); if(b=='-') { map[i][j]=1; } else{ map[i][j]=0; } } getchar(); } flag=0; for(int i=0;i<=16;++i){//判断i步是否可以达到目标 ans=i; dfs(1,1,0); if(flag) //遍历 { break; } } if(flag) //如果能成功达到,就输出 { printf("%d\n",ans);//需要几次 for(int i=0;i<ans;++i){ printf("%d %d\n",a[i].p,a[i].q); } } return 0; }
标签:handle,int,flip,dfs,handles,POJ2965,include,open,refrigerator 来源: https://www.cnblogs.com/pipihoudewo/p/10464059.html