Number of Islands

Problem

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

Concept

The idea is to find the total number of connected components. Although we can use Union Find, it can be solved with DFS.

Algorithm

  1. Initialize the result variable to 0.

  2. Iterate over each cell in the grid.

  3. If the cell is land, then:

    • Recursively call the dfs function on the cell.

    • Increment the result variable by 1.

  4. Return the result variable.

The dfs function works as follows:

  1. Check if the current cell is out of bounds or if it is already visited. If it is, then return.

  2. Mark the current cell as visited.

  3. Recursively call the dfs function on the four neighbors of the current cell.

Code

Last updated