http://poj.org/problem?id=1753
Flip Game
Description 1 Flip game is played on a rectangular 4x4 field with two-sided pieces placed on each of its 16 squares. One side of each piece is white and the other one is black and each piece is lying either it's black or white side up. Each round you flip 3 to 5 pieces, thus changing the color of their upper side from black to white and vice versa. The pieces to be flipped are chosen every round according to the following rules: 2 Flip the chosen piece and also all adjacent pieces to the left, to the right, to the top, and to the bottom of the chosen piece (if there are any).
Input The input consists of 4 lines with 4 characters "w" or "b" each that denote game field position. Output Write to the output file a single integer number - the minimum number of rounds needed to achieve the goal of the game from the given position. If the goal is initially achieved, then write 0. If it's impossible to achieve the goal, then write the word "Impossible" (without quotes). Sample Input bwwb bbwb bwwb bwww Sample Output 4 Source |
[Submit] [Go Back] [Status] [Discuss]
解析:状态枚举,其实暴力法也可行
#include<stdio.h>
#include<string.h>
#include <iostream>
using namespace std;
int ch[5][5];
int cnt=33;
char st[10];
void turnover(int i,int j)
{
if(i>=0&&i<=3&&j>=0&&j<=3)
ch[i][j]=!ch[i][j];
}
void flip(int s)
{
int i=s/4;
int j=s%4;
turnover(i,j);
turnover(i+1,j);
turnover(i,j+1);
turnover(i-1,j);
turnover(i,j-1);
}
bool complete()
{
int s=0;
for(int i=0;i<=3;i++)
for(int j=0;j<=3;j++)
s+=ch[i][j];
if(s%16==0)
return true;
else
return false;
}
void dfs(int id,int nu)
{
if(complete())
{if(cnt>nu)
cnt=nu;
return;
}
if(id>=16)
return;
dfs(id+1,nu);
flip(id);
dfs(id+1,nu+1);
flip(id);
}
int main()
{
int i,j;
memset(ch,0,sizeof(ch));
for(i=0;i<4;i++)
{
scanf("%s",st);
for(j=0;j<4;j++)
if(st[j]=='w')
ch[i][j]=1;
}
dfs(0,0);
if(cnt==33)
printf("Impossible\n");
else
printf("%d\n",cnt);
return 0;
}
相关博客:http://hi.baidu.com/lxxstar1226/item/bf7891df67251510d68ed078
http://hi.baidu.com/lxxstar1226/item/bf7891df67251510d68ed078