156. Islands After Each Arrival
Hard
You are given a grid that is initially covered by water. Grid rows and columns are indexed starting at zero.
Each element of posicoes identifies a cell that becomes land. Two land cells belong to the same island if one can reach the other using only land cells that share a side; cells that touch only diagonally are not neighbors.
After processing each position, return the number of islands at that moment. If a position has already been added, it does not change the grid, but it must still produce an answer in the list.
Example 1
Input: linhas = 3, colunas = 3, posicoes = [[0,0],[0,1],[1,2],[2,1],[1,1]]
Output: [1,1,2,3,1]
Explanation: The last position connects the three existing islands.
Example 2
Input: linhas = 2, colunas = 2, posicoes = [[0,0],[1,1]]
Output: [1,2]
Explanation: Diagonal cells do not belong to the same island.
Example 3
Input: linhas = 2, colunas = 2, posicoes = [[0,0],[0,0],[1,0],[1,1]]
Output: [1,1,1,1]
Explanation: The repeated position does not create a new island.
Constraints
- 1 <= linhas, colunas <= 10^4
- 1 <= linhas * colunas <= 10^5
- 1 <= posicoes.length <= 10^5
- Each element of posicoes has exactly two integers: [linha, coluna].
- 0 <= linha < linhas and 0 <= coluna < colunas for every position.
Union-findMatrix
Saved in this browser
Caso 1
linhas =
3
colunas =
3
posicoes =
[[0,0],[0,1],[1,2],[2,1],[1,1]]
Expected =
[1,1,2,3,1]
Caso 2
linhas =
2
colunas =
2
posicoes =
[[0,0],[1,1]]
Expected =
[1,2]
Caso 3
linhas =
2
colunas =
2
posicoes =
[[0,0],[0,0],[1,0],[1,1]]
Expected =
[1,1,1,1]
Run checks these 3 cases. Submit runs all 12, including hidden ones.