| Time Limit: 1000MS | Memory Limit: 65536K | |
| Total Submissions: 34437 | Accepted: 15058 |
Description
Consider the following position as an example:Input
Output
Sample Input
bwwb bbwb bwwb bwww
Sample Output
4
#include<iostream>
#include<cstdio>
#define INF 0x3f3f3f3f
using namespace std;
string s[4];
int num=INF;
int a[10][10];
int panduan()
{
for(int i=0;i<4;i++)
for(int j=0;j<4;j++)
if(a[i][j]!=a[0][0])
return 0;
return 1;
}
int fanzhuan(int x,int y)
{
a[x][y]=!a[x][y];
if(x<3)
a[x+1][y]=!a[x+1][y];
if(x>0)
a[x-1][y]=!a[x-1][y];
if(y>0)
a[x][y-1]=!a[x][y-1];
if(y<3)
a[x][y+1]=!a[x][y+1];
}
int DFS(int x,int y,int ans)
{
if(panduan())
{if(num>ans)
num=ans;
return 0;
}
if(x>3||y>3)
return 0;
int fx,fy;
fx=(x+1)%4; //按列来翻转
fy=(x+1)/4+y;
//每个位置都有2种情况 全部跑一遍
fanzhuan(x,y); //翻成另一面
DFS(fx,fy,ans+1);
fanzhuan(x,y); //还原
DFS(fx,fy,ans);
}
int main()
{
while(cin>>s[0])
{
for(int i=1;i<4;i++)
cin>>s[i];
for(int i=0;i<4;i++)
for(int j=0;j<4;j++)
if(s[i][j]=='w')
a[i][j]=1;
else
a[i][j]=0;
DFS(0,0,0);
if(num!=INF)
cout<<num;
else
cout<<"Impossible";
cout<<endl;
}
}
<span id="transmark">DFS+枚举,时间相对少些</span>
#include<iostream>
#include<cstring>
using namespace std;
int num=0x3f3f3f3f;
int a[13][15],flag;
int panduan ()
{
for(int i=0;i<4;i++)
for(int j=0;j<4;j++)
if(a[i][j]!=a[0][0])
return 0;
return 1;
}
int fanzhuan(int x,int y)
{
a[x][y]=!a[x][y];
if(x>0)
a[x-1][y]=!a[x-1][y];
if(x<3)
a[x+1][y]=!a[x+1][y];
if(y<3)
a[x][y+1]=!a[x][y+1];
if(y>0)
a[x][y-1]=!a[x][y-1];
}
int DFS(int x,int y,int ans)
{
if(num==ans)
{flag=panduan();
return 0;
}
if(x>3||y>3||flag)
return 0;
int fx=(x+1)%4;
int fy=(x+1)/4+y;
fanzhuan(x,y); //此处顺序不能变
DFS(fx,fy,ans+1);
fanzhuan(x,y);
DFS(fx,fy,ans);
return 0;
}
int main()
{
string s[4];
for(int i=0;i<4;i++)
cin>>s[i];
for(int i=0;i<4;i++)
for(int j=0;j<4;j++)
if(s[i][j]=='w')
a[i][j]=1;
else
a[i][j]=0;
flag=0;
for(int i=0;i<=16;i++) //枚举,..最多16次
{
num=i;
DFS(0,0,0);
if(flag)
break;
}
if(flag)
cout<<num;
else
cout<<"Impossible";
cout<<endl;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文:http://blog.csdn.net/became_a_wolf/article/details/47323429