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.

Input & Output

example_1.py — Basic Islands
$ Input: grid = [["1","1","1","1","0"],["1","1","0","1","0"],["1","1","0","0","0"],["0","0","0","0","0"]]
Output: 1
💡 Note: All the 1's are connected horizontally or vertically, forming one large island surrounded by water.
example_2.py — Multiple Islands
$ Input: grid = [["1","1","0","0","0"],["1","1","0","0","0"],["0","0","1","0","0"],["0","0","0","1","1"]]
Output: 3
💡 Note: There are three separate islands: one 2x2 island in top-left, one single cell in middle, and one 1x2 island in bottom-right.
example_3.py — Single Cell
$ Input: grid = [["1"]]
Output: 1
💡 Note: Edge case with just one cell containing land forms exactly one island.

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 ≤ m, n ≤ 300
  • grid[i][j] is '0' or '1'
  • Grid cells contain only characters '0' and '1'

Visualization

Tap to expand
Number of Islands - DFS Approach INPUT 2D Grid Map (4x5) 1 1 1 1 0 1 1 0 1 0 1 1 0 0 0 0 0 0 0 0 = Land (1) = Water (0) grid = [ ["1","1","1","1","0"],["1","1","0","1","0"], ["1","1","0","0","0"],["0","0","0","0","0"]] ALGORITHM STEPS 1 Scan Grid Iterate through each cell 2 Find Land (1) When found, increment count 3 DFS Exploration Mark all connected land 4 Mark Visited Change 1 to 0 (sink island) DFS Traversal Pattern S 2 3 4 5 S=Start, numbers show order Directions: Up, Down, Left, Right FINAL RESULT After DFS completes: All land cells are connected! Red outline = Single Island OUTPUT 1 OK - One island found! Key Insight: DFS acts like "flooding" - when we find land, we explore ALL connected land cells recursively. By marking visited cells (changing 1 to 0), we ensure each island is counted exactly once. Time Complexity: O(M x N) where M=rows, N=cols | Space Complexity: O(M x N) for recursion stack TutorialsPoint - Number of Islands | DFS Approach
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28 Apple 22
67.8K Views
Very High Frequency
~15 min Avg. Time
2.3K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen