codekofi
← All problems

Problem 103

Medium

1 · Worked examples

0 / 3

Type an input and write what you think is the output . Each problem is converted to Web Assembly, so any possible input will show the corresponding output. Only correct predictions count.

solution()
returns

2 · Which problem is it?

Locked until you have predicted 3 outputs correctly.

The accepted solution

1void spare(vector<string>& grid, int r, int c) {
2
3 int rows = grid.size();
4 int cols = grid[0].size();
5
6 if (r < 0 || r >= rows || c < 0 || c >= cols) {
7 return;
8 }
9
10 if (grid[r][c] != 'O') {
11 return;
12 }
13
14 grid[r][c] = 'T';
15
16 spare(grid, r + 1, c);
17 spare(grid, r - 1, c);
18 spare(grid, r, c + 1);
19 spare(grid, r, c - 1);
20}
21
22vector<string> solution(vector<string> grid) {
23
24 if (grid.empty() || grid[0].empty()) {
25 return grid;
26 }
27
28 int rows = grid.size();
29 int cols = grid[0].size();
30
31 for (int r = 0; r < rows; r++) {
32 spare(grid, r, 0);
33 spare(grid, r, cols - 1);
34 }
35
36 for (int c = 0; c < cols; c++) {
37 spare(grid, 0, c);
38 spare(grid, rows - 1, c);
39 }
40
41 for (int r = 0; r < rows; r++) {
42 for (int c = 0; c < cols; c++) {
43
44 if (grid[r][c] == 'O') {
45 grid[r][c] = 'X';
46 } else if (grid[r][c] == 'T') {
47 grid[r][c] = 'O';
48 }
49 }
50 }
51
52 return grid;
53}

Names have been stripped. The signature is the only clue you get for free. Compiled as C++20 with the standard headers and using namespace std; already in scope.