思路是别人的,自己理解了半天,真是渣渣。对于自己,项目和算法总不能兼得,路还长,年轻人。
思路:
1. 对任意一个格子来说,翻动偶数次等于没翻,翻动奇数次等于翻一次,所以只需考虑翻一次的情况。
2. 一共16个格子,每个格子只有翻和不翻,所以最多16步,最少0步,题目要求最少的步数,所以0——>16枚举,看哪一步先成功就是最优解。
3. 使用dfs,要考虑到树根时如果还没成功,要回溯;回溯时要把棋子再翻回来,再搜。
#include <iostream>
using namespace std;
bool chess[6][6]={false};
int step;
bool flag;
int r[5]={-1,1,0,0,0};//row up,down,left,right,o
int c[5]={0,0,-1,1,0};//col up,down,left,right,o
//judge whether to the end
bool isOver()
{
int i,j;
for(i=1;i<5;i++)
{
for(j=1;j<5;j++)
{
if(chess[i][j]!=chess[1][1])
{
return false;
}
}
}
return true;
}
//change all adjacent pieces
void flip(int row,int col)
{
int i;
for(i=0;i<5;i++)
{
chess[row+r[i]][col+c[i]]=!chess[row+r[i]][col+c[i]];
}
}
void dfs(int row,int col,int deep)
{
if(deep==step)
{
flag=isOver();
return;
}
if(flag || row==5)
{
return;
}
flip(row,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;
//initial
for(i=1;i<5;i++)
{
for(j=1;j<5;j++)
{
cin>>temp;
if('b'==temp)
{
chess[i][j]=true;
}
}
}
//function
for(step=0;step<=16;step++)
{
dfs(1,1,0);
if(flag)
{
break;
}
}
//result
if(flag)
{
cout<<step<<endl;
}
else
{
cout<<"Impossible"<<endl;
}
//system("pause");
return 0;
}