This problem requires a classic data structure called UnionFind. Take some efforts to learn it at first, like using this Princeton's notes offered by peisi. This note is very nicely written. Take some patinece to read through it and you will get a tool that is also helpful in the future :-)
Operation #1: addLand(0, 0) turns the water at grid into a land.
Operation #3: addLand(1, 2) turns the water at grid into a land.
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).
Operation #2: addLand(0, 1) turns the water at grid into a land.
We return the result as an array:
[1, 1, 2, 3]
Operation #4: addLand(2, 1) turns the water at grid into a land.
The C++ code is as follows, taking peisi's Java code as an example.
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.