Number of Islands
Difficulty: Easy · Topic: Pathfinding
Given a grid of 0 (water) and 1 (land), return the number of islands. An island is a group of 1s connected 4-directionally (up/down/left/right). Flood-fill each unvisited land cell with BFS or DFS and count how many fills you start.
Examples
num_islands([[1,1,0,0],[1,0,0,1],[0,0,1,1]])
→ 2A left L-shape and a right block.
num_islands([[1]])
→ 1Target complexity: time O(R·C), space O(R·C)
Write your solution in Python and run it against hidden tests right on this page. Progressive hints and Python + C++ reference solutions are included.
Learn the idea first: the lesson for this problem.