codekofi
← All problems

Problem 14

Medium

1 · Worked examples

0 / 4

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 4 outputs correctly.

The accepted solution

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

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.