Back

Graph Algorithms (Hard) / 276. Number of Islands

00:00
1/5

276. Number of Islands

Medium

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.

Example:

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

    Traversal: We need to traverse every "1" node and its neighbors.

  • 2

    DFS/BFS: When we find a "1", invoke a DFS/BFS to visit all connected "1"s and mark them as visited (e.g., turn them to "0" or usage a visited set).

  • 3

    Count: Each time we start a new DFS/BFS from the main loop, we have found a new island. Increment count.

PYTHON PLAYGROUND
PYTHON PLAYGROUND
⏳ Loading editor…