Input: ‘M’ = 3, 'N' = 3, 'POSITIONS' = [ [ 0,0 ], [ 0,1 ], [ 1,2 ], [ 2,1 ] ]
Output: [1, 1, 2, 3]
Initially, the 2d 'GRID' is filled with water.
- Operation #1: addLand(0, 0) turns the water at ‘GRID[0][0]’ into a land. We have 1 island.
- Operation #2: addLand(0, 1) turns the water at ‘GRID[0][1]’ into a land. We still have 1 island.
- Operation #3: addLand(1, 2) turns the water at 'GRID[1][2]’ into a land. We have 2 islands.
- Operation #4: addLand(2, 1) turns the water at 'GRID[2][1]’ into a land. We have 3 islands.
The first line contains ‘T’, denoting the number of test cases.
The first line of each test case contains two integers, ‘N’ and ‘M’, denoting the number of rows and columns in the 'GRID'.
The second line of each test case contains an integer ‘K’ denoting the size of ‘POSITION’ array.
Each of the next ‘K’ lines contains two space-separated integers denoting the (‘Ri’, ‘Ci’) of ‘POSITION[i]’.
For each test case, return the array of integers as described in the problem statement.
You don't need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= M, N, K <= 100
0 <= Ri< m
0 <= Ci < n
Time Limit: 1 sec
Linear scan the 2d grid map, if a node contains a '1', then it is a root node that triggers a Depth First Search. During DFS, every visited node should be set as '0' to mark it as a visited node. Count the number of root nodes that trigger DFS, this number would be the number of islands since each DFS starting at some root identifies an island.
Treat the 2d 'GRID' map as an undirected graph (formatted as adjacency matrix) and there is an edge between two horizontally or vertically adjacent nodes of value 1, then the problem reduces to finding the number of connected components in the graph after each ‘addLand’ operation.