27 / 75
M

Number of Islands

#27
graphdfsbfs+2

Use DFS/BFS to flood-fill islands and count connected components.

Example:

Input:[['1','1','0','0','0'],['1','1','0','0','0'],['0','0','1','0','0'],['0','0','0','1','1']]
Output:3

Common Mistakes:

  • Not marking cells as visited (infinite recursion or wrong count)
  • Using separate visited array when you can modify grid in-place
  • Forgetting to check boundaries in DFS/BFS
  • Counting diagonal connections (problem only allows 4-directional)

Notes:

Classic connected components problem. Time O(m*n), Space O(m*n) for recursion stack. Can also solve with Union-Find or BFS.

27/75
Number of Islands