Imagine you're a cartographer analyzing satellite imagery of an archipelago! You have a 2D grid map where '1' represents land and '0' represents water. Your mission is to count how many separate islands exist in this region.
An island is formed by connecting adjacent land cells ('1's) either horizontally or vertically (diagonal connections don't count). Think of it like walking from one piece of land to another - you can only move up, down, left, or right.
Example: If you see connected land masses, they form a single island. Separate land masses surrounded by water are different islands.
The entire grid is surrounded by water, so any land on the edges is still considered part of an island if connected to other land.
G
Google 45a
Amazon 38f
Meta 32⊞
Microsoft 28
Apple 22
Number of Islands — Solution
The optimal approach uses graph traversal (DFS or BFS) to explore connected components. When we find an unvisited land cell, we increment our island count and use DFS/BFS to mark the entire connected island as visited. This ensures each island is counted exactly once with O(m × n) time complexity.
Common Approaches
✓
BFS with Queue (Optimal)
⏱️ Time: O(m × n)
Space: O(min(m, n))
Similar to DFS approach but uses Breadth-First Search with a queue. When we find a '1', we add it to queue and explore all connected land cells level by level. This avoids potential stack overflow issues with deep recursion and provides iterative solution.
Brute Force with DFS
⏱️ Time: O(m × n)
Space: O(m × n)
Iterate through every cell in the grid. When we find a '1' (land), we increment our island count and use Depth-First Search to mark all connected land cells as visited (change them to '0' or use a visited array). This prevents counting the same island multiple times.
BFS with Queue (Optimal) — Algorithm Steps
Initialize island counter and create a queue
Iterate through each cell in the grid
When we find a '1', increment counter and add to queue
Use BFS to explore all connected cells from queue
Mark visited cells and add new land neighbors to queue
Continue until queue is empty, then resume grid scan
Visualization
Tap to expand
Step-by-Step Walkthrough
1
Find Island Start
Discover first land cell of new island
2
Add to Queue
Add starting cell to BFS queue
3
Explore Level
Process all cells at current level
4
Add Neighbors
Add adjacent land cells to queue
5
Complete Island
Continue until entire island is explored
Code -
solution.c — C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
int r, c;
} Point;
typedef struct {
Point* data;
int front, rear, capacity;
} Queue;
Queue* createQueue(int capacity) {
Queue* q = (Queue*)malloc(sizeof(Queue));
q->data = (Point*)malloc(sizeof(Point) * capacity);
q->front = q->rear = 0;
q->capacity = capacity;
return q;
}
void enqueue(Queue* q, Point p) {
q->data[q->rear] = p;
q->rear = (q->rear + 1) % q->capacity;
}
Point dequeue(Queue* q) {
Point p = q->data[q->front];
q->front = (q->front + 1) % q->capacity;
return p;
}
int isEmpty(Queue* q) {
return q->front == q->rear;
}
void bfs(char** grid, int rows, int cols, int start_r, int start_c, int directions[4][2]) {
Queue* queue = createQueue(rows * cols);
enqueue(queue, (Point){start_r, start_c});
grid[start_r][start_c] = '0';
while (!isEmpty(queue)) {
Point curr = dequeue(queue);
int r = curr.r;
int c = curr.c;
for (int i = 0; i < 4; i++) {
int nr = r + directions[i][0];
int nc = c + directions[i][1];
if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && grid[nr][nc] == '1') {
grid[nr][nc] = '0';
enqueue(queue, (Point){nr, nc});
}
}
}
free(queue->data);
free(queue);
}
int numIslands(char** grid, int gridSize, int* gridColSize) {
if (gridSize == 0 || gridColSize[0] == 0) {
return 0;
}
int rows = gridSize;
int cols = gridColSize[0];
int islands = 0;
int directions[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
if (grid[r][c] == '1') {
islands++;
bfs(grid, rows, cols, r, c, directions);
}
}
}
return islands;
}
int main() {
char input[10000];
fgets(input, sizeof(input), stdin);
char* gridStart = strstr(input, "[[");
if (!gridStart) {
printf("0\n");
return 0;
}
// Count rows by counting opening brackets after the first one
int rows = 0;
char* p = gridStart + 1;
while (*p) {
if (*p == '[') rows++;
p++;
}
if (rows == 0) {
printf("0\n");
return 0;
}
char** grid = (char**)malloc(rows * sizeof(char*));
int* gridColSize = (int*)malloc(rows * sizeof(int));
p = gridStart + 1;
for (int i = 0; i < rows; i++) {
// Find start of row
while (*p && *p != '[') p++;
if (!*p) break;
p++; // skip [
// Count columns by counting quoted characters
char* rowStart = p;
int cols = 0;
while (*p && *p != ']') {
if (*p == '"') cols++;
p++;
}
cols /= 2; // Each element has 2 quotes
gridColSize[i] = cols;
grid[i] = (char*)malloc(cols * sizeof(char));
// Extract characters
p = rowStart;
int colIdx = 0;
while (*p && *p != ']' && colIdx < cols) {
if (*p == '"') {
p++; // skip opening quote
grid[i][colIdx++] = *p;
p++; // skip the character
if (*p == '"') p++; // skip closing quote
} else {
p++;
}
}
while (*p && *p != ']') p++;
if (*p == ']') p++;
}
int result = numIslands(grid, rows, gridColSize);
printf("%d\n", result);
for (int i = 0; i < rows; i++) {
free(grid[i]);
}
free(grid);
free(gridColSize);
return 0;
}
Time & Space Complexity
Time Complexity
⏱️
O(m × n)
Each cell is visited exactly once, either during grid scan or BFS traversal
n
2n
✓ Linear Growth
Space Complexity
O(min(m, n))
Queue size can be at most min(m,n) in worst case when BFS explores diagonally
n
2n
⚡ Linearithmic Space
67.8K Views
Very HighFrequency
~15 minAvg. Time
2.3K Likes
Ln 1, Col 1
Smart Actions
💡Explanation
AI Ready
💡 SuggestionTabto acceptEscto dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen
Algorithm Visualization
Pinch to zoom • Tap outside to close
Test Cases
0 passed
0 failed
3 pending
Select Compiler
Choose a programming language
Compiler list would appear here...
AI Editor Features
Header Buttons
💡
Explain
Get a detailed explanation of your code. Select specific code or analyze the entire file. Understand algorithms, logic flow, and complexity.
🔧
Fix
Automatically detect and fix issues in your code. Finds bugs, syntax errors, and common mistakes. Shows you what was fixed.
💡
Suggest
Get improvement suggestions for your code. Best practices, performance tips, and code quality recommendations.
💬
Ask AI
Open an AI chat assistant to ask any coding questions. Have a conversation about your code, get help with debugging, or learn new concepts.
Smart Actions (Slash Commands)
🔧
/fix Enter
Find and fix issues in your code. Detects common problems and applies automatic fixes.
💡
/explain Enter
Get a detailed explanation of what your code does, including time/space complexity analysis.
🧪
/tests Enter
Automatically generate unit tests for your code. Creates comprehensive test cases.
📝
/docs Enter
Generate documentation for your code. Creates docstrings, JSDoc comments, and type hints.
⚡
/optimize Enter
Get performance optimization suggestions. Improve speed and reduce memory usage.
AI Code Completion (Copilot-style)
👻
Ghost Text Suggestions
As you type, AI suggests code completions shown in gray text. Works with keywords like def, for, if, etc.
Tabto acceptEscto dismiss
💬
Comment-to-Code
Write a comment describing what you want, and AI generates the code. Try: # two sum, # binary search, # fibonacci
💡
Pro Tip: Select specific code before using Explain, Fix, or Smart Actions to analyze only that portion. Otherwise, the entire file will be analyzed.