题目
题解思路
时间复杂度 2 的16次方 。
啊这,我太高估它了!
对每个位置进行翻转或者不翻转的操作,翻转了记得回溯,当到遍历完所有位置时,检查有没有答案,如果有就更新,更新出来的答案还可以剪枝操作。
看来以后要先算算时间复杂度了!!!
AC代码
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <cmath>
#include <vector>
using namespace std;
int dx[4] = {-1,1,0,0};
int dy[4] = {0,0,-1,1};
int mp[5][5];
int ans = 99999999;
int che()
{
int a = mp[0][0];
for (int i = 0 ; i < 4 ; i++ )
for (int k = 0 ;k < 4 ; k++ )
if ( mp[i][k] != a )
return 0;
return 1;
}
void sw(int x,int y)
{
mp[x][y] = !mp[x][y];
for (int i = 0 ; i < 4 ; i++ )
{
int fx = x + dx[i];
int fy = y + dy[i];
if ( fx >= 0 && fx < 4 && fy >= 0 && fy < 4 )
{
mp[fx][fy] = !mp[fx][fy];
}
}
}
void dfs(int d,int step)
{
if ( step > ans )
return ;
int x,y;
if ( d == 16 )
{
if (che() == 1 )
ans = min(step,ans);
return ;
}
x = d/4 ;
y = d%4 ;
dfs(d+1,step);
sw(x,y);
dfs(d+1,step+1);
sw(x,y);
}
int main ()
{
char a;
for (int i = 0 ; i < 4 ; i++ )
for (int k = 0 ;k < 4 ; k++ )
{
cin>>a;
if ( a == 'b' )
mp[i][k] = 1;
else
mp[i][k] = 0;
}
dfs(0,0);
if (ans == 99999999)
cout<<"Impossible"<<endl;
else
cout<<ans<<"\n";
return 0;
}