DEV Community

Harsh Prajapat
Harsh Prajapat

Posted on

The Number of Islands problem is a popular LeetCode question (Problem #200):

Problem Statement:
Given a 2D grid map of '1's (land) and '0's (water), count the number of islands.
An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically.

βœ… Swift Solution Using DFS

func numIslands(_ grid: [[Character]]) -> Int {
    if grid.isEmpty { return 0 }

    var grid = grid  // make a mutable copy
    let rows = grid.count
    let cols = grid[0].count
    var islandCount = 0

    func dfs(_ r: Int, _ c: Int) {
        if r < 0 || c < 0 || r >= rows || c >= cols || grid[r][c] == "0" {
            return
        }

        grid[r][c] = "0" // mark as visited
        dfs(r + 1, c)
        dfs(r - 1, c)
        dfs(r, c + 1)
        dfs(r, c - 1)
    }

    for r in 0..<rows {
        for c in 0..<cols {
            if grid[r][c] == "1" {
                islandCount += 1
                dfs(r, c)
            }
        }
    }

    return islandCount
}

// Example usage
let inputGrid: [[Character]] = [
    ["1","1","0","0","0"],
    ["1","1","0","0","0"],
    ["0","0","1","0","0"],
    ["0","0","0","1","1"]
]

print("Number of islands: \(numIslands(inputGrid))") // Output: 3
Enter fullscreen mode Exit fullscreen mode

🧠 Explanation:

Traverse the grid cell-by-cell.

When a '1' is found, it's the start of an island β†’ increment count.

Use DFS to visit and mark all connected land as '0' (visited).

⏱️ Time Complexity:

O(m Γ— n): Every cell is visited once.

Top comments (0)