Q2
unknown
c_cpp
16 days ago
3.7 kB
6
Indexable
Never
#include <stdio.h> // Use two 2D matrices to store the temperoary result of each day // mapA is used to store the temperoray result of each day // mapB is used to store the result after the update, and will be used to update on mapA after everything is done each day int mapA[300][300], mapB[300][300]; int main() { // Read in the arguments int H, W, D; scanf("%d %d %d", &H, &W, &D); // Readin the value of each box in mapA for (int i = 0; i < H; i++) for (int j = 0; j < W; j++) scanf("%d", &mapA[i][j]); // First loop through each day for (int d = 0; d < D; d++) { // The second and third will go through each box in the matrix for (int i = 0; i < H; i++) { for (int j = 0; j < W; j++) { // The first section, we are going the calculate the voting result. // We use three variables as the counter of each category: int rock = 0, paper = 0, scissor = 0; // Loop through the eight boxes around current box (i, j) for (int di = -1; di <= 1; di++) { // di means the difference in i axis compared with current box (i, j) for (int dj = -1; dj <= 1; dj++) { // dj means the difference in j axis compared with current box (i, j) // Use (ti, tj) to represent the box we are going to inspect int ti = i + di, tj = j + dj; // Check the validity of the inspected box // 1. (ti != i && tj != j): Is it NOT the current box? // 2. (ti >= 0 && ti < H && tj >= 0 && tj < W): Is the value of coordinate valid? if ((ti != i && tj != j) && (ti >= 0 && ti < H && tj >= 0 && tj < W)) { // If all the condition is held, we will increase the counter of corresponding category if (mapA[ti][tj] == 0) rock += 1; else if (mapA[ti][tj] == 2) scissor += 1; else if (mapA[ti][tj] == 5) paper += 1; } } } // In the second section, we are going to update the result to mapB based on the counters we've updated: // (Since it is the majority voting, we cannot use `>=` !!) if (rock > paper && rock > scissor) mapB[i][j] = 5; // If majority is rock, update to paper else if (paper > rock && paper > scissor) mapB[i][j] = 2; // If majority is paper, update to scissor else if (scissor > rock && scissor > paper) mapB[i][j] = 0; // If majority is scissor, update to stone else mapB[i][j] = mapA[i][j]; // Otherwise, copy the current value } } // After all the boxes are updated, we need to copy the current value back to mapA, // then in the next day, we can read in the correct value of each box after the voting today for (int i = 0; i < H; i++) for (int j = 0; j < W; j++) mapA[i][j] = mapB[i][j]; } // Once we update D days, we can ouput the result of mapA for (int i = 0; i < H; i++) { for (int j = 0; j < W; j++) { printf("%d ", mapA[i][j]); } printf("\n"); } return 0; }
Leave a Comment