0200. Number of Islands
Medium | BFS + DFS | 128 ms (94.03%), 15.2 MB (95.17%)
Last updated
Was this helpful?
Medium | BFS + DFS | 128 ms (94.03%), 15.2 MB (95.17%)
Last updated
Was this helpful?
Source: GitHub:
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.
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.