A - Flip Game

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:

  1. Choose any one of the 16 pieces.
  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).


Consider the following position as an example:

bwbw
wwww
bbwb
bwwb
Here "b" denotes pieces lying their black side up and "w" denotes pieces lying their white side up. If we choose to flip the 1st piece from the 3rd row (this choice is shown at the picture), then the field will become:

bwbw
bwww
wwwb
wwwb
The goal of the game is to flip either all pieces white side up or all pieces black side up. You are to write a program that will search for the minimum number of rounds needed to achieve this goal.

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

这题网上的思路很多,自己先写一个dfs的方法。

怎么dfs呢?一共16个格子,每个格子也只有2中状态。用step记录翻动的次数,0<=step<=16。

相当于对每个step值进行搜索,遍历每一个状态。

#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
bool g[6][6];
int dir[5][2]={0,0,0,1,0,-1,1,0,-1,0};
int step;
bool flag;

void flip(int x,int y)
{
    for(int i=0;i<5;i++)
    {
        int nx=x+dir[i][0],ny=y+dir[i][1];
        g[nx][ny]=!g[nx][ny];
    }
}

bool check()
{
    for(int i=1;i<=4;i++)
        for(int j=1;j<=4;j++)
            if(g[i][j]!=g[1][1]) return false;
    return true;
}

void dfs(int x,int y,int dep)
{
    if(step==dep)
    {
        flag=check();
        return;
    }
    else if(flag||x==5) return;
    flip(x,y);
    if(y<4) dfs(x,y+1,dep+1);
    else dfs(x+1,1,dep+1);
    flip(x,y);
    if(y<4) dfs(x,y+1,dep);
    else dfs(x+1,1,dep);
}

int main()
{
    for(int i=1;i<=4;i++)
    {
        for(int j=1;j<=4;j++)
        {
            char c;
            scanf("%c",&c);
            if(c=='w') g[i][j]=true;
            else g[i][j]=false;
        }
        getchar();
    }
    for(step=0;step<=16;step++)
    {
        dfs(1,1,0);
        if(flag) break;
    }
    if(!flag) puts("Impossible");
    else printf("%d\n", step);
    return 0;
}

 

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页