Skip to content

Prepare For Coder Interview – Denny

  • Basic
  • Medium
  • Hard
  • Architect
  • Life

LeetCode: Number of Islands II

Posted on February 27, 2018July 26, 2020 by braindenny

Number of Islands II



Similar Problems:

  • Series: Island & Follow-up
  • CheatSheet: Leetcode For Code Interview
  • CheatSheet: Common Code Problems & Follow-ups
  • Tag: #graph, #unionfind, #graphchangecell, #island

A 2d grid map of m rows and n columns is initially filled with water. We may perform an addLand operation which turns the water at position (row, col) into a land. Given a list of positions to operate, count the number of islands after each addLand operation. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

Example:

Given m = 3, n = 3, positions = [[0,0], [0,1], [1,2], [2,1]].
Initially, the 2d grid grid is filled with water. (Assume 0 represents water and 1 represents land).

0 0 0
0 0 0
0 0 0

Operation #1: addLand(0, 0) turns the water at grid[0][0] into a land.

1 0 0
0 0 0   Number of islands = 1
0 0 0

Operation #2: addLand(0, 1) turns the water at grid[0][1] into a land.

1 1 0
0 0 0   Number of islands = 1
0 0 0

Operation #3: addLand(1, 2) turns the water at grid[1][2] into a land.

1 1 0
0 0 1   Number of islands = 2
0 0 0

Operation #4: addLand(2, 1) turns the water at grid[2][1] into a land.

1 1 0
0 0 1   Number of islands = 3
0 1 0

We return the result as an array: [1, 1, 2, 3]

Challenge:

Can you do it in time complexity O(k log mn), where k is the length of the positions?

Github: code.dennyzhang.com

Credits To: leetcode.com

Leave me comments, if you have better ways to solve.


// https://code.dennyzhang.com/number-of-islands-ii
// Basic Ideas: unionfind
//
//  When add a new position, check with 4 adjacent cells
//  If no adjacent islands, increase the counter
//  Otherwise, the counter may be the same or decrease
//
// Complexity: Time O(m*n+k), Space O(m*n)
type UF struct {
    parent []int
    groupCnt int
}

func constructor(size int) UF {
    parent := make([]int, size)
    for i, _ := range parent {
        parent[i] = i
    }
    return UF{parent:parent}
}

func (uf *UF) union(x, y int) {
    n1, n2 := uf.find(x), uf.find(y)
    if n1 == n2 {
        return
    }
    if n1>n2{
        n1,n2 = n2,n1
        x,y = y,x
    }
    uf.parent[n2] = n1
    uf.groupCnt--
}

func (uf *UF) find(x int) int {
    // TODO: path compression
    for uf.parent[x] != x {
        x = uf.parent[x]
    }
    return x
}

func numIslands2(m int, n int, positions [][]int) []int {
    uf := constructor(m*n)
    grid := make([][]int, m)
    for i, _ := range grid {
        grid[i] = make([]int, n)
    }
    res := make([]int, len(positions))
    for k, p := range positions {
        i, j := p[0], p[1]
        // if current cell is already island, no change
        if grid[i][j] == 0 {
            grid[i][j] = 1
            uf.groupCnt++
            for _, offset := range [][]int{[]int{1, 0}, []int{-1, 0}, []int{0, 1}, []int{0, -1}} {
                i2, j2 := i+offset[0], j+offset[1]
                if i2<0 || i2>=m || j2<0 || j2>=n {
                    continue
                }
                if grid[i2][j2] == 1 {
                    n1, n2 := i*n+j, i2*n+j2
                    uf.union(n1, n2)
                }
            }
        }
        res[k] = uf.groupCnt
    }
    return res
}
linkedin
github
slack

Post Views: 1
Posted in MediumTagged #graph, graphchangecell, island, unionfind

Post navigation

LeetCode: Base 7
LeetCode: Degree of an Array

Leave a Reply Cancel reply

Your email address will not be published.

Tags

#array #backtracking #bfs #binarytree #bitmanipulation #blog #classic #codetemplate #combination #dfs #dynamicprogramming #game #graph #greedy #heap #inspiring #interval #linkedlist #manydetails #math #palindrome #recursive #slidingwindow #stack #string #subarray #trie #twopointer #twosum binarysearch editdistance hashmap intervaldp knapsack monotone oodesign presum rectangle redo review rotatelist series sql treetraversal unionfind

Recent Posts

  • a
  • a
  • a
  • a
  • a

Recent Comments

    Archives

    Categories

    • Amusing
    • Basic
    • Easy
    • Hard
    • Life
    • Medium
    • Resource
    • Review
    • Series
    • Uncategorized
    Proudly powered by WordPress | Theme: petals by Aurorum.