Solving LeetCode's Number of Islands: A Deep Dive into DFS
benono
Posted on November 30, 2024
Introduction
The Number of Islands problem is a classic example of depth-first search (DFS) application in grid traversal. In this article, I'll walk you through my thought process and implementation strategy.
Let me explain my approach to the Number of Islands problem.
Problem Understanding
This problem can be categorized as a grid traversal pattern where we need to:
- Count the number of distinct islands
- Define an island as a group of connected '1's
- Handle the grid modification efficiently
Approach
I'll use DFS (Depth-First Search) for this problem because:
- It's a natural fit for exploring connected components
- We can modify the input grid to track visited cells
- It provides a clean recursive solution
Implementation Strategy
Let me break down the key components:
- Main Function:
- Iterate through each cell in the grid
- When we find a '1', increment our island counter
- Start DFS exploration from that cell
- DFS Helper Function:
- Check boundary conditions
- Verify if current cell is part of an island
- Mark visited cells
- Explore in all four directions
Edge Cases
- Empty grid
- Single row/column grid
- Grid with no islands
- Grid with all islands
Complexity Analysis
- Time: O(M × N) where M is rows and N is columns
- Space: O(M × N) worst case for the recursion stack
Key Optimization
Instead of using a separate visited set, we modify the input grid directly by marking visited cells with a different value. This approach:
- Saves space
- Simplifies our logic
- Maintains the connected component property
My Implementation
/**
* @param {character[][]} grid
* @return {number}
*/
var numIslands = function (grid) {
// We start with a counter and grid size
var count = 0;
const y = grid.length;
const x = grid[0].length;
// Handles the recursive exploration
function dfs(i, j) {
if (i < 0 || i >= y || j < 0 || j >= x || grid[i][j] !== "1") return;
// Mark the cell as visited
grid[i][j] = "0";
dfs(i - 1, j);
dfs(i, j + 1);
dfs(i + 1, j);
dfs(i, j - 1);
}
// Main loop to iterate through the grid
for (let i = 0; i < grid.length; i++) {
for (let j = 0; j < grid[i].length; j++) {
if (grid[i][j] === "1") {
count++;
dfs(i, j);
}
}
}
return count;
};
const grid = [
["1", "1", "0", "0", "0"],
["1", "1", "0", "0", "0"],
["0", "0", "1", "0", "0"],
["0", "0", "0", "1", "1"],
];
console.log(numIslands(grid));
💖 💪 🙅 🚩
benono
Posted on November 30, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.