Skip to main content

Understanding Number of Islands | Flood Fill & Graph DFS Explained

How to Solve “Number of Islands” Using Flood Fill and Graph Traversal

When solving grid-based problems, it often feels confusing when explanations suddenly label the problem as a “graph problem” even though no graph is visible. This article explains the Number of Islands problem by connecting it to a much more intuitive idea — the 4-connected flood fill algorithm commonly taught in computer graphics.

Problem Overview

You are given a 2D grid containing "1" (land) and "0" (water). An island is formed when land cells are connected horizontally or vertically. The task is to count how many such islands exist in the grid.


Input:
[
  ["1","1","0","0"],
  ["1","0","0","1"],
  ["0","0","1","1"],
  ["0","1","0","0"]
]

Output: 3

Thinking in Terms of Flood Fill

If you have previously implemented flood fill in computer graphics, this problem should feel familiar. In flood fill, we start from a pixel and keep filling neighboring pixels until we hit a boundary or a different color.

In this problem:

  • Land ("1") acts as the target color
  • Water ("0") acts as the boundary
  • Up, down, left, and right represent 4-connected neighbors

Once we encounter a land cell, we “fill” the entire connected region and mark it as visited.

Where the Graph Comes In

Although no graph is explicitly drawn, the grid itself forms an implicit graph. Each cell is a node, and each cell is connected to its adjacent neighbors.

  • Each grid cell is a node
  • Edges exist between horizontally and vertically adjacent cells
  • Only land cells ("1") are considered part of the graph

This is why the problem is often described as a graph traversal problem. We are simply traversing connected components in an implicit graph.

Depth-First Search (DFS) Traversal

The solution works by scanning the grid cell by cell. Whenever an unvisited land cell is found, a depth-first search is started to visit all connected land cells.

  1. Traverse the entire grid
  2. When land is found, increment the island count
  3. Use DFS to visit and mark all connected land cells
  4. Continue until all cells are processed

Marking a cell as visited is done by converting land ("1") into water ("0"). This prevents the same island from being counted multiple times.

Core DFS Logic


def dfs(i, j):
    if out_of_bounds or grid[i][j] == "0":
        return
    grid[i][j] = "0"
    dfs(i + 1, j)
    dfs(i - 1, j)
    dfs(i, j + 1)
    dfs(i, j - 1)

This logic is identical to flood fill: stop at boundaries, mark visited cells, and explore neighbors.

Why This Approach Works

  • Each cell is visited only once
  • Connected land cells are grouped together
  • Each DFS call corresponds to exactly one island

The time complexity is O(rows × columns), since every cell is processed once. The space complexity is also O(rows × columns) in the worst case due to the recursion stack.

Complete Implementation


class Solution:
    def visit_cell(self, i, j, size):
        if i < 0 or i > size[0] or j < 0 or j > size[1] or self.grid[i][j] == "0":
            return 

        self.grid[i][j] = "0"
        self.visit_cell(i+1, j, size)
        self.visit_cell(i, j+1, size)
        self.visit_cell(i-1, j, size)
        self.visit_cell(i, j-1, size)

    def numIslands(self, grid: List[List[str]]) -> int:
        self.grid = grid
        answer = 0
        for i in range(len(grid)):
            for j in range(len(grid[0])):
                if self.grid[i][j] != "0":
                    self.visit_cell(i, j, (len(grid) - 1, len(grid[0]) - 1))
                    answer += 1
        return answer

Conclusion

The Number of Islands problem does not require an explicitly built graph. Instead, it relies on recognizing that a grid can behave like a graph and that flood fill is simply a form of graph traversal.

If you understand flood fill, you already understand DFS on a grid. This realization makes many grid-based problems much easier to approach.

Full source code is available here: https://github.com/RohitSingh-04/Python-Solutions/blob/main/LC200.py

Comments

Popular posts from this blog

Introducing CodeMad: Your Ultimate Universal IDE with Custom Shortcuts

Introducing CodeMad: Your Ultimate Multi-Language IDE with Custom Shortcuts Welcome to the world of CodeMad, your all-in-one Integrated Development Environment (IDE) that simplifies coding and boosts productivity. Developed in Python, CodeMad is designed to make your coding experience smoother and more efficient across a variety of programming languages, including C, C++, Java, Python, and HTML. Whether you're a beginner or an experienced programmer, CodeMad is your go-to tool. In this blog, we'll dive deep into the workings of CodeMad, highlighting its unique features and easy installation process. The Power of Shortcuts CodeMad's intuitive interface is built around a set of powerful keyboard shortcuts that make coding a breeze. Here are some of the key shortcuts you'll find in CodeMad: Copy (Ctrl+C) : Duplicate text with ease. Paste (Ctrl+V) : Quickly insert copied content into your code. Undo (Ctrl+Z) and Redo (Ctrl+Y) : Correct mistakes and s...

LeetCode 88 Explained: Four Approaches, Mistakes, Fixes & the Final Optimal Python Solution

Evolving My Solution to “Merge Sorted Array” A practical, beginner-friendly walkthrough showing four versions of my code (from a naive approach to the optimal in-place two-pointer solution). Includes explanations, complexity and ready-to-paste code. Problem Summary You are given two sorted arrays: nums1 with size m + n (first m are valid) nums2 with size n Goal: Merge nums2 into nums1 in sorted order in-place . Version 1 — Beginner Approach (Extra List) I merged into a new list then copied back. Works, but not in-place and uses extra memory. class Solution: def merge(self, nums1, m, nums2, n): result = [] p1 = 0 p2 = 0 for _ in range(m+n): if p1 >= m: result.extend(nums2[p2:n]) break elif p2 >= n: result.extend(nums1[p1:m]) break elif nu...

How do I run Python on Google Colab using android phone?

Regardless of whether you are an understudy keen on investigating Machine Learning yet battling to direct reproductions on huge datasets, or a specialist playing with ML frantic for extra computational force, Google Colab is the ideal answer for you. Google Colab or "the Colaboratory" is a free cloud administration facilitated by Google to support Machine Learning and Artificial Intelligence research, where frequently the obstruction to learning and achievement is the necessity of gigantic computational force. Table of content- What is google colab? how to use python in google colab? Program to add two strings given by the user. save the file in google colab? What is google colab? You will rapidly learn and utilize Google Colab on the off chance that you know and have utilized Jupyter notebook previously. Colab is fundamentally a free Jupyter notebook climate running completely in the cloud. In particular, Colab doesn't need an arrangement, in addition to the notebook tha...