CP: The largest island

A map shows land (#) and water (.). Land cells that touch up, down, left or right belong to the same island. Find the size of the largest island, in cells.

What to build

Visit every cell. When you meet land that has not been seen, run a DFS (or flood fill) from it that returns the number of cells it marks, and keep the largest.

Requirements

  • Use DFS on the grid with four neighbours
  • Check the bounds before reading a cell
  • Print 0 when there is no land

Input

The first line has R and C. Each of the next R lines has C characters, # or ..

Output

The number of cells in the largest island.

Constraints

1 ≤ R, C ≤ 30.

Example

Input:

4 5
##...
#..#.
...##
.#.#.

Output:

4

Why it works

The DFS marks every land cell connected to its start, so each island is visited once and its cells are counted once. Trying every unseen land cell as a start covers all islands, and the maximum of the sizes is the answer.

Examples

Example 1 · Input
4 5
##...
#..#.
...##
.#.#.
Expected output
4
Example 2 · Input
2 2
..
..
Expected output
0

Hints

Hint 1

int dfs(int r, int c) marks the cell and returns 1 plus the sum of dfs over the four neighbours that are land and unseen.

Hint 2

Use dr[] and dc[] and check 0 <= nr < R and 0 <= nc < C first.

Hint 3

The recursion goes at most 900 deep.

Solution

Show one correct solution (try it yourself first)
#include <iostream>
#include <string>
#include <vector>
using namespace std;

int R, C;
vector<string> grid;
vector<vector<bool> > seen;

int dfs(int r, int c) {
    seen[r][c] = true;
    int size = 1;
    int dr[] = {1, -1, 0, 0}, dc[] = {0, 0, 1, -1};
    for (int k = 0; k < 4; k++) {
        int nr = r + dr[k], nc = c + dc[k];
        if (nr < 0 || nc < 0 || nr >= R || nc >= C) continue;
        if (grid[nr][nc] != '#' || seen[nr][nc]) continue;
        size += dfs(nr, nc);
    }
    return size;
}

int main() {
    cin >> R >> C;
    grid.resize(R);
    for (auto& row : grid) cin >> row;
    seen.assign(R, vector<bool>(C, false));
    int best = 0;
    for (int r = 0; r < R; r++)
        for (int c = 0; c < C; c++)
            if (grid[r][c] == '#' && !seen[r][c]) {
                int s = dfs(r, c);
                if (s > best) best = s;
            }
    cout << best << "\n";
    return 0;
}

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: Depth-first search and components →