題目鏈接
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:
Choose any one of the 16 pieces.
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.
輸入描述:
The input consists of 4 lines with 4 characters “w” or “b” each that denote game field position.
輸出描述:
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).
示例1
輸入
bwwb
bbwb
bwwb
bwww
輸出
4
題意:
有一4x4棋盤,上面有16枚雙面棋子(一面為黑,一面為白),
當翻動一只棋子時,該棋子上下左右相鄰的棋子也會同時翻面,
以b代表黑面,w代表白面,給出一個棋盤狀態,
問從該棋盤狀態開始,使棋盤變成全黑或全白,至少需要翻轉多少步
解題思路
列舉每一種情況;每一種情況都要判斷是否滿足題目要求;如果有滿足要求的,就找出滿足要求并且改變點最少的那一個情況;每一種情況都不滿足則輸出“Impossible”;也可以使用BFS、DFS求解,
#include<stdio.h>
#include<iostream>
#include<string>
using namespace std;
typedef long long ll;
char a[5][5];
bool all = 0;
int mm = 100;
void bian(int n, int m)
{
for(int i = -1; i <= 1; i++)
for(int j = -1; j <= 1; j++)
{
if(i * j == 1 || i * j == -1) continue; //四個方向(上,下,左,右)和本身保留,其他方向都排除
if(1 <= n + i && n + i <= 4 && 1 <= m + j && m + j <= 4)//判斷是否在范圍內
{
if(a[n + i][m + j] == 'b') a[n + i][m + j] = 'w';
else a[n + i][m + j] = 'b';
}
}
}
bool pan()
{
char c = a[1][1];
for(int i = 1; i <= 4; i++)
for(int j = 1; j <= 4; j++)
if(a[i][j] != c) return false;
return true;
}
void meiju(int n, int m, int num)
{
for(int i = 1; i <= 4; i++)
{
for(int j = 1; j <= 4; j++)
{
if(i < n || (i == n && j <= m)) continue;
bian(i, j); //改變
if(pan() && num < mm)
{
mm = num;
all = true;
}
meiju(i, j, num + 1);
bian(i, j); //還原
}
}
}
int main()
{
for(int i = 1; i <= 4; i++)
for(int j = 1; j <= 4; j++)
cin >> a[i][j];
if(pan()) //判斷一開始的字符是否滿足要求
{
mm = 0;
all = true;
}
else meiju(0, 0, 1);
if(all) cout << mm << endl;//判斷是否找到滿足要求的情況
else cout << "Impossible" << endl;
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/263359.html
標籤:其他
上一篇:C語言走迷宮小游戲
