POJ 1753 Flip Game (DFS + 暴力枚举)

来源:互联网 发布:k3无法数据引出 编辑:程序博客网 时间:2024/06/05 14:08

Flip Game
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 44428 Accepted: 19079

Description

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

bwwbbbwbbwwbbwww

Sample Output

4

题意:翻翻棋,棋子有黑白两面,当翻一个棋子时,该棋子四周围都会被翻过来,黑的变成白的,白的变成黑的。

思路:DFS遍历16个点,每个点的都有两种动作,要么翻,要么不翻,每次遍历到下一个点的时候,检查整个棋盘是否符合要求,注意回溯。

代码如下:

#include<cstdio>#include<iostream>#include<cmath>using namespace std;char mp[5][5];int map[5][5];int dir[4][2]={1, 0, -1, 0, 0, 1, 0, -1};int flag = 0, step = 0x3f3f3f3f;int check(){//判断当前状态是否符合要求 int i, j, pre;pre = map[0][0];for(i = 0; i < 4; i++){for(j = 0; j < 4; j++){if(pre != map[i][j])return 0;}}return 1;}void function(int x, int y){//翻盘 map[x][y] = !map[x][y];for(int i = 0; i < 4; i++){int tx = x + dir[i][0];int ty = y + dir[i][1];if(tx >= 0 && tx < 4 && ty >= 0 && ty < 4){map[tx][ty] = !map[tx][ty];}}} void dfs(int m, int cnt){//dfs遍历每个点 if(m > 15){if(check()){step = min(cnt, step);flag = 1;}return;}if(check()){step = min(cnt, step);//取最小的次数 flag = 1;return;}int x = m / 4;int y = m % 4;dfs(m + 1, cnt);//如果不翻 function(x, y);//翻 dfs(m + 1, cnt + 1);//如果翻 function(x, y);//回溯 return;}int main(){int n, i, j, x;for(i = 0; i < 4; i++){scanf("%s", mp[i]);}for(i = 0; i < 4; i++){for(j = 0; j < 4; j++){if(mp[i][j] == 'b'){map[i][j] = 0;}else{map[i][j] = 1;}}}dfs(0, 0);if(flag)cout<<step<<endl;else cout<<"Impossible"<<endl;return 0;}

0 0
原创粉丝点击