这道题目与poj1753的解题思路非常相似。
区别在于翻转的时候方式稍微不一样,不过这不影响算法的中心思想。
#include<iostream>
using namespace std;
bool refrigerator[5][5] = {false};
int step;
bool flag = false;
class node
{
public:
int row;
int col;
};
node steps[16+1];
bool judge_all()
{
int i,j;
for(i = 1;i<=4;i++)
for(j = 1; j<=4;j++)
if(refrigerator[i][j] == false)
return false;
return true;
}
void flip(int row,int col)
{
int i;
for(i = 1;i<=4;i++)
{
refrigerator[i][col] = !refrigerator[i][col];
refrigerator[row][i] = !refrigerator[row][i];
}
refrigerator[row][col] = !refrigerator[row][col];
}
void dfs(int row,int col,int deep)
{
if(step == deep)
{
flag = judge_all();
return;
}
if(row > 4 || flag ) return ;
flip(row,col);
// 将步伐记录在数组中
steps[deep+1].row = row;
steps[deep+1].col = col;
if(col < 4)
dfs(row,col+1,deep+1);
else dfs(row+1,1,deep+1);
flip(row,col);
if(col< 4)
dfs(row,col+1,deep);
else dfs(row+1,1,deep);
return;
}
int main()
{
int i,j;
char temp;
for(i = 1;i<=4;i++)
for(j = 1; j<=4 ; j++)
{
cin>>temp;
if(temp == '-')
refrigerator[i][j] = true;
}
for(step = 0; step <= 16 ; step ++)
{
dfs(1,1,0);
if(flag) break;
}
if(flag)
cout<<step<<endl;
else cout<<"Impossible"<<endl;
for(int q = 1;q<=step;q++)
cout<<steps[q].row<<" "<<steps[q].col<<endl;
//system("pause");
return 0;
}