200. Number of Islands

Medium

Problem:

Given a 2D grid map where 1 represents land and 0 represents water, calculate the number of islands (determine the number of connected groups of 1s).

Input:
  11110
  11010
  11000
  00000
Output: 1
Input:
  11000
  11000
  00100
  00011
Output: 3

https://leetcode.com/problems/number-of-islands/arrow-up-right

Solution:

DFS

By completing the search in each of the four directions using DFS recursion, we can determine the number of lands by incrementing 1.

  1. Here, based on the input value 'grid', we search row by row and column by column for land (1). When land is discovered, we initiate the search by calling the dfs() function.

  2. At this time, the places that have been visited are marked with a value other than 1. This ensures they aren't recalculated in subsequent iterations. It's a form of pruning.

BFS

Reference: https://www.youtube.com/watch?v=pV2kpPD66nEarrow-up-right

Last updated