1057. 石头剪刀布
题目描述
Bart的妹妹Lisa在一个二维矩阵上创造了新的文明。矩阵上每个位置被三种生命形式之一占据:石头,剪刀,布。每天,上下左右相邻的不同生命形式将会发生战斗。在战斗中,石头永远胜剪刀,剪刀永远胜布,布永远胜石头。每一天结束之后,败者的领地将被胜者占领。
你的工作是计算出n天之后矩阵的占据情况。
输入
第一行包含三个正整数r,c,n,分别表示矩阵的行数、列数以及天数。每个整数均不超过100。
接下来r行,每行c个字符,描述矩阵初始时被占据的情况。每个位置上的字符只能是R,S,P三者之一,分别代表石头,剪刀,布。相邻字符之间无空格。
输出
输出n天之后的矩阵占据情况。每个位置上的字符只能是R,S,P三者之一,相邻字符之间无空格。
样例输入
3 3 1
RRR
RSR
RRR
样例输出
RRR
RRR
RRR
数据范围限制
C++代码
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
const int max_num = 100;
char BattleMatrix[max_num+2][max_num+2];
char NewBattleMatrix[max_num+2][max_num+2];
void PrintBattleMatrix(char Matrix[max_num+2][max_num+2], int r, int c)
{
for(int i=1; i<=r; i++)
{
for(int j=1; j<=c; j++)
{
cout << Matrix[i][j];
}
cout << endl;
}
}
void Fight(char OldMatrix[][max_num+2], char NewMatrix[][max_num+2], int r, int c)
{
struct _Step
{
int dx; // delta_x
int dy; // delta_y
} Moves[4] = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}}; // move up/right/down/left
for(int i=1; i<=r; i++)
{
for(int j=1; j<=c; j++)
{
if (OldMatrix[i][j] == 'R')
{
for (int step=1; step<=4; step++)
{
if (OldMatrix[i+Moves[step-1].dx][j+Moves[step-1].dy] == 'S')
{
NewMatrix[i+Moves[step-1].dx][j+Moves[step-1].dy] = 'R';
}
}
}
else if (OldMatrix[i][j] == 'S')
{
for (int step=1; step<=4; step++)
{
if (OldMatrix[i+Moves[step-1].dx][j+Moves[step-1].dy] == 'P')
{
NewMatrix[i+Moves[step-1].dx][j+Moves[step-1].dy] = 'S';
}
}
}
else if (OldMatrix[i][j] == 'P')
{
for (int step=1; step<=4; step++)
{
if (OldMatrix[i+Moves[step-1].dx][j+Moves[step-1].dy] == 'R')
{
NewMatrix[i+Moves[step-1].dx][j+Moves[step-1].dy] = 'P';
}
}
}
}
}
}
int main()
{
int r, c, n; // r: row, c: column, n: days
cin >> r >> c >> n;
// initialize BattleMatrix
memset(BattleMatrix, 0 , sizeof(BattleMatrix));
for(int i=1; i<=r; i++)
{
cin >> BattleMatrix[i]+1;
}
memcpy(NewBattleMatrix, BattleMatrix, sizeof(BattleMatrix));
for (int d=1; d<=n; d++)
{
if(d & 1)
{
Fight(BattleMatrix, NewBattleMatrix, r, c);
memcpy(BattleMatrix, NewBattleMatrix, sizeof(BattleMatrix));
}
else
{
Fight(NewBattleMatrix, BattleMatrix, r, c);
memcpy(NewBattleMatrix, BattleMatrix, sizeof(BattleMatrix));
}
}
PrintBattleMatrix(NewBattleMatrix, r, c);
return 0;
}