AAlgoLoopSpaced repetition for LeetCode
MEDIUMBFS / DFSLeetCode ↗

Number of Islands

The key idea

Every time you find a new land cell that has not been visited, that is the start of a brand-new island. Flood-fill the whole island so its cells are never counted again, then keep scanning.

Problem

You are given an m x n 2-D grid grid of '1's (land) and '0's (water). Return the number of islands.

An island is a group of land cells connected 4-directionally (up, down, left, right). You may assume all four edges of the grid are surrounded by water.

Land cells that touch only diagonally are not connected and belong to different islands.

Constraints

Examples

Input: grid = [["1","1","0"],["1","0","0"],["0","0","0"]] Output: 1
Input: grid = [["1","1","0","0"],["0","0","0","1"],["0","0","0","0"],["1","0","0","0"]] Output: 3

Complexity

Time: O(m*n) Space: O(m*n)

See the full solution

410310
Step-by-step visualization
Start free →

More BFS / DFS problems