Graphs Union-find
465. Number of Islands II
You are given the size of a map, m rows and n columns. At first every cell is water. Then land is added
one cell at a time: positions[i] = [r, c] turns the cell in row r and column c into land.
An island is a group of land cells joined by steps up, down, left or right. Two land cells that touch only at a corner are not joined. Everything outside the map is water.
Return a list with one number per position: the number of islands right after that cell is added. A position can appear more than once. Adding land to a cell that is already land changes nothing.
Example 1
Input: m = 3
n = 4
positions = [[0, 0],
[0, 1],
[1, 2],
[2, 1],
[0, 3],
[1, 1]]
[1,1,2,3,4,2]Explanation: Cell (0,1) joins the island at (0,0). Cells (1,2), (2,1) and (0,3) each start a new island, which makes four. The last cell, (1,1), touches the islands at (0,1), (1,2) and (2,1), so those three and the new cell become one island. With (0,3), that leaves two.
Example 2
Input: m = 2
n = 2
positions = [[0, 0],
[1, 1],
[0, 1],
[1, 0],
[0, 0]]
[1,2,1,1,1]Explanation: Cell (0,1) joins the two corner islands into one. Cell (1,0) touches two land cells too, but they are already one island, so the count stays 1. The last position is already land, so nothing changes.
Example 3
Input: m = 1
n = 5
positions = [[0, 4],
[0, 0],
[0, 2],
[0, 1],
[0, 3]]
[1,2,3,2,1]Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ m, n ≤ 104m × n ≤ 1061 ≤ positions.length ≤ 105positions[i].length == 20 ≤ ri < m,0 ≤ ci < n
Clarifying questions
What you would ask an interviewer before writing any code.