0200. Number of Islands
Medium | BFS + DFS | 128 ms (94.03%), 15.2 MB (95.17%)
Source: LeetCode - Number of Islands GitHub: Solution / Performance
Given an m x n
2D binary grid grid
which represents a map of '1'
s (land) and '0'
s (water), return the number of islands.
An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
We could solve this problem by either DFS or BFS method. (BFS requires less memory usage)
DFS
We recursively explore the whole map subject to the boundary condition for moving up, down, left, and right and whether the current location is an island or not.
BFS
We iteratively explore the whole map by using a stack to record the visited island subject to the boundary condition for moving up, down, left, and right and whether the current location is an island or not.
Last updated