Number of Islands

DFS

Problem

Given an m x n 2d grid 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.

Constraints:

  • m == grid.length

  • n == grid[i].length

  • 1 <= m, n <= 300

  • grid[i][j] is '0' or '1'.

For 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
Input: grid = [
  ["1","1","0","0","0"],
  ["1","1","0","0","0"],
  ["0","0","1","0","0"],
  ["0","0","0","1","1"]
]
Output: 3

Thought Process

  • DFS is a good approach since we are dealing with connected components as well as neighboring cells and switching/marking the visited components

  • Our DFS cycle will break once we are out of bounds or come across a element that is not a '1'

  • We are utilizing DFS to change/mark the visited cells and recurssing on its neighboring cells

Solution

Time Complexity

  • Time: O(m*n) since we are traversing the whole matrix

  • Space: O(m*n) for the recursion stack b/c worst case if we have all 1's then it's like a snake pattern in terms of stack calls

Last updated

Was this helpful?