题目链接:
http://poj.org/problem?id=2965
题目大意就是一个4*4的方阵只有“+”“-”两种,当变换一个位置的符号时,该符号所在的行和列所有符号都要变换,问全部变成“-”号时最少要几步,并以此输出变换的位置!
一维数组存图很巧妙,处理的时候比二维方便的多!
/4取横坐标, %4取纵坐标!
#include<iostream>
using namespace std;
bool arc[16];
int posi[16];
int posj[16];
bool check()
{
for(int i=0;i<16;i++)
{
if(!arc[i])
return false;
}
return true;
}
bool DFS(int pos,int step)
{
if(check())
{
printf("%d\n",step);
for(int i=0;i<step;i++)
printf("%d %d\n",posi[i],posj[i]);
return true;
}
if(pos>=16)
return false;
if(DFS(pos+1,step))
return true;
flip(pos);
posi[step]=pos/4+1;
posj[step]=pos%4+1;
if(DFS(pos+1,step+1))
return true;
flip(pos);
return false;
}
void flip(int pos)
{
int i=pos/4;
int j=pos%4;
arc[pos]=!arc[pos];
for(int m=0;m<4;m++)
{
arc[i*4+m]=!arc[i*4+m];
arc[m*4+j]=!arc[m*4+j];
}
}
int main()
{
char ch;
for(int i=0;i<16;i++)
{
cin>>ch;
if(ch=='+')
arc[i]=0;
else
arc[i]=1;
}
DFS(0,0);
return 0;
}