Challenge: Count the Islands
Completed
In a map of # (land) and . (water), land cells touching up/down/left/right form one island. Print the number of islands and the size of the biggest (0 if there's no land).
Input
Line 1: rows cols. Then rows lines of # and ..
Output
Islands: <count> Biggest: <size>
Example
Input
4 5 ##..# #...# ..#.. .....
Output
Islands: 3 Biggest: 3
Editor
C++
Hints
Each # you haven't visited starts an island.
Flood-fill it with BFS, counting cells and turning them into water.
Solution explanation
Every cell is processed at most once: O(rows × cols).
Show solution
#include <algorithm>
#include <iostream>
#include <queue>
#include <string>
#include <vector>
using namespace std;
int main() {
int R, C;
cin >> R >> C;
vector<string> g(R);
for (auto& row : g) cin >> row;
int count = 0, biggest = 0;
int dr[] = {1, -1, 0, 0}, dc[] = {0, 0, 1, -1};
for (int r = 0; r < R; r++)
for (int c = 0; c < C; c++) {
if (g[r][c] != '#') continue;
count++;
int size = 0;
queue<pair<int, int>> q;
q.push({r, c});
g[r][c] = '.';
while (!q.empty()) {
auto [y, x] = q.front();
q.pop();
size++;
for (int d = 0; d < 4; d++) {
int ny = y + dr[d], nx = x + dc[d];
if (ny >= 0 && ny < R && nx >= 0 && nx < C && g[ny][nx] == '#') {
g[ny][nx] = '.';
q.push({ny, nx});
}
}
}
biggest = max(biggest, size);
}
cout << "Islands: " << count << endl;
cout << "Biggest: " << biggest << endl;
return 0;
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module