题目链接:点击打开链接
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
<span style="font-size:18px;">#include<iostream>
#include<cstring>
using namespace std;
bool mp[4][4]= {false};
int step;
bool f;
struct node//存储走过的路径
{
int x,y;
} q[1000];
int top;
bool judge()//判断是否为"-"号
{
for(int i=0; i<4; i++)
{
for(int j=0; j<4; j++)
{
if(mp[i][j]==false)
{
return false;
}
}
}
return true;
}
void turn(int x,int y)//将所在的行和列转换
{
for(int i=0; i<4; i++)
{
mp[x][i]=!mp[x][i];
}
for(int i=0; i<4; i++)
{
if(i!=x)
{
mp[i][y]=!mp[i][y];
}
}
}
void dfs(int x,int y,int deep)//深搜可行路径
{
if(deep==step)//枚举步数
{
top=0;//**在每次到达相应步数时top清零
f=judge();
return ;
}
if(f||x==4)return ;
turn(x,y);
if(y<3)
dfs(x,y+1,deep+1);
else
dfs(x+1,0,deep+1);
q[top].x=x+1;//在回溯时将路径记录下来,此时路径的方向是反的(因为是回溯的时候)
q[top++].y=y+1;
turn(x,y);//还原开关状态图
if(y<3)
dfs(x,y+1,deep);
else
dfs(x+1,0,deep);
return ;
}
int main()
{
char ch;
for(int i=0; i<4; i++)
{
for(int j=0; j<4; j++)
{
cin>>ch;
if(ch=='-')mp[i][j]=true;
}
}
for(step=0; ; step++)
{
dfs(0,0,0);
if(f)break;
}
cout<<step<<endl;
for(int i=top-1; i>=0; i--)//倒着输出为正确路径(因为是回溯时记录的)
{
cout<<q[i].x<<" "<<q[i].y<<endl;
}
return 0;
}
</span>