DevPath

← All problems

Number of Islands

Medium matrix · graphs

Description

A grid of 0s and 1s where 1s are land. Return the number of islands (land connected horizontally or vertically).

Constraints

1 <= rows, cols <= 300

Examples

Input: grid = [[1,1,0],[0,1,0],[0,0,1]]

Output: 2

Hints (1)
  • Flood fill each unvisited land cell.

Solutions

DFS flood fill. · Time O(rows*cols) · Space O(rows*cols)

func numIslands(grid [][]int) int {
    rows, cols := len(grid), len(grid[0])
    g := make([][]int, rows)
    for i := range grid {
        g[i] = append([]int{}, grid[i]...)
    }
    var sink func(r, c int)
    sink = func(r, c int) {
        if r < 0 || c < 0 || r >= rows || c >= cols || g[r][c] != 1 {
            return
        }
        g[r][c] = 0
        sink(r+1, c); sink(r-1, c); sink(r, c+1); sink(r, c-1)
    }
    count := 0
    for r := 0; r < rows; r++ {
        for c := 0; c < cols; c++ {
            if g[r][c] == 1 {
                count++
                sink(r, c)
            }
        }
    }
    return count
}

Create a free account to submit solutions, track progress and save problems.

Create account