此题被http://www.acmwiki.com/index.php?doc-view-8.htm 归为初级题,知道方法后确实简单,套用DFS模版即可
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 <iostream>
#include <iomanip>
#include <string>
#include <algorithm>
#include <functional>
#include <vector>
#include <list>
#include <queue>
#include <utility>
#include <sstream>
#include <cctype>
#include <cstdio>
#include <cstring>
#include <cmath>
using namespace std;
int step;
bool handles[4][4];//门把手
bool solutions[4][4];//解决方案
bool flag=false;//问题解决与否标志
bool isOK()//判断是否解决
{
for(int i=0;i<16;i++)
if(handles[i/4][i%4]==false)
return false;
return true;
}
void switch_handle(int row,int colum)//旋转门把手
{
for(int i=0;i<4;i++)
{
handles[row][i]=!handles[row][i];
handles[i][colum]=!handles[i][colum];
}
handles[row][colum]=!handles[row][colum];//多旋了一次,补回来
}
void dfs(int row,int colum,int dep)//DFS递归查找
{
if(dep==step)
{
flag=isOK();
return;
}
if(flag || row==4)return;
switch_handle(row,colum);//旋转
if(!flag)solutions[row][colum]=true;//保存旋转位置
if(colum<3)dfs(row,colum+1,dep+1);
else dfs(row+1,0,dep+1);
switch_handle(row,colum);//旋转回来
if(!flag)solutions[row][colum]=false;//清除旋转位置
if(colum<3)dfs(row,colum+1,dep);
else dfs(row+1,0,dep);
}
int main()
{
for(int i=0;i<16;i++)
{
char c;
cin>>c;
handles[i/4][i%4]=(c=='-')?true:false;
}
memset(solutions,0,sizeof(solutions));
for(step=0;step<=16;step++)
{
dfs(0,0,0);
if(flag)break;
}
cout<<step<<endl;
for (int i=0;i<16;i++)
{
if(solutions[i/4][i%4]==true)
cout<<i/4+1<<" "<<i%4+1<<endl;
}
return 0;
}