codekofi
← All problems

Problem 14

Medium40 XP

1 · Worked examples

0 / 4

Give it an input and say what you think comes back. It compiles and runs for real, so a wrong guess still shows you the answer — probe as much as you like. 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 int rows = grid.size();
3 int cols = grid[0].size();
4 if (r < 0 || r >= rows) return;
5 if (c < 0 || c >= cols) return;
6 if (grid[r][c] != '1') return;
7
8 grid[r][c] = '0';
9 flood(grid, r + 1, c);
10 flood(grid, r - 1, c);
11 flood(grid, r, c + 1);
12 flood(grid, r, c - 1);
13}
14
15int solution(vector<vector<char>> grid) {
16 if (grid.empty() || grid[0].empty()) return 0;
17 int rows = grid.size();
18 int cols = grid[0].size();
19 int found = 0;
20 for (int r = 0; r < rows; r++) {
21 for (int c = 0; c < cols; c++) {
22 if (grid[r][c] == '1') {
23 found++;
24 flood(grid, r, c);
25 }
26 }
27 }
28 return found;
29}

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.