This problem is one of the most straightforward ones I have seen, so if you are struggling then you are probably doing something wrong. In that case see if the following hints help:
(1) As someone mentioned before, it's probably easier to figure out how a given cell will change based on its neighboring cells than to figure out the opposite. More explicitly, if the current cell is Scissors, it will be a Rock only if one of its neighbors is a Rock.
(2) Like many other problems, if you are storing data for a r-by-c grid, you might want to define char [r+2][c+2] instead of char [r][c] and store the data in the middle so that you don't have to do all the boundary checking. I find this quite helpful, especially for all those problems involving chessboards.
(3) Really can't think of any other tip. Just make sure you output a blank line BETWEEN cases.
I tried testing my code with self-created test cases and it seems to work fine but I keep on getting WA. What is wrong with my code?
Thank you for helping.
#include <iostream>
using namespace std;
int r, c, n;
char original[101][101], duplicate[101][101];
bool winner(char y, char x) {
if (x == 'R' && y == 'S')
return true;
if (x == 'S' && y == 'P')
return true;
if (x == 'P' && y == 'R')
return true;
return false;
}
void battle (int i, int j) {
bool defeat;
if (j < c - 1) { // if not last column, combat with right side
defeat = false;
defeat = winner(original[i][j], original[i][j + 1]);
if (defeat) {
duplicate[i][j] = original[i][j + 1];
return;
}
}
if (j > 0) { // if not first column, combat with left side
defeat = false;
defeat = winner(original[i][j], original[i][j - 1]);
if (defeat) {
duplicate[i][j] = original[i][j - 1];
return;
}
}
if (i != 0) { // if not first row, combat with top
defeat = false;
defeat = winner(original[i][j], original[i - 1][j]);
if (defeat) {
duplicate[i][j] = original[i - 1][j];
return;
}
}
if (i < r - 1) { // if not last row, combat with bottom
defeat = false;
defeat = winner(original[i][j], original[i + 1][j]);
if (defeat) {
duplicate[i][j] = original[i + 1][j];
return;
}
}
duplicate[i][j] = original[i][j];
return;
}
int main() {
int tc;
cin >> tc;
while (tc--) {
cin >> r >> c >> n;
cin.ignore();
for (int i = 0; i < r; ++i) {
cin.getline(original[i], 100);
}
for (int i = 0; i < n; ++i) {
for (int m = 0; m < r; ++m) {
for (int n = 0; n < c; ++n) {
battle(m, n);
//cout << duplicate[m][n];
}
//cout << endl;
}
for (int m = 0; m < r; ++m) {
for (int n = 0; n < c; ++n) {
original[m][n] = duplicate[m][n];
}
}
}
for (int i = 0; i < r; ++i) {
for (int j = 0; j < c; ++j) {
cout << original[i][j];
}
cout << endl;
}
if (tc)
cout << endl;
}
return 0;
}