# Number of Islands II

Posted: 21 Mar, 2021
Difficulty: Hard

## PROBLEM STATEMENT

#### An island is a group of lands surrounded by water horizontally, vertically, or diagonally.

##### Input Format:
``````The first line contains an integer ‘T’ denoting the number of test cases.

The first input line of each test case contains two single space-separated integers ‘N’ and ‘M’ representing the number of rows and columns of the grid, respectively.

The second line of each test case contains an integer ‘Q’ representing the number of queries.

Next ‘Q’ lines contain two single space-separated integers ‘X’ and ‘Y’, representing the coordinates of the grid i.e the coordinates of the point to be turned into land.
``````
##### Output Format:
``````For each test case, print a single integer denoting the number of islands after each query operation.

Print the output of each test case in a separate line.
``````
##### Note:
``````You are not required to print the expected output; it has already been taken care of. Just implement the given function.
``````
##### Constraints:
``````1 <= T <= 5
1 <= N <= 1000
1 <= M <= 1000
1 <= Q <= 100000
0 <= X < N
0 <= Y < M

Time limit: 1 sec
`````` Approach 1

The idea here is to represent the grid as a graph and all the adjacent land cells are connected via an edge. Finally, do DFS on the grid and find the number of connected components after each query operation.

The algorithm is as follows:

1. Declare an ‘ANS’ array to store the number of islands after each query.
2. Declare a 2D array 'GRID' with ‘N’ rows and ‘M’ columns, where ‘GRID[i][j]’ = 0 or 1, 0 representing water and 1 representing land.
3. Declare a ‘DX’ array representing and set it to {1, 0, -1, 0}, representing the directions of all four neighboring cells.
4. Declare a ‘DY’ array representing and set it to {0, 1, 0, -1}, representing the directions of all four neighboring cells.
5. Iterate from ‘P’ = 0 to ‘Q.size() - 1’,
• Declare a variable ‘X’ and set it to ‘Q[i]’.
• Declare a variable ‘Y’ and set it to 'Q[i]'.
• Set ‘GRID[X][Y]’ to 1, i.e i.e cell is converted into the land.
• Declare a variable 'NUMBEROFISLANDS' and set it to 0.
• Declare a 2D array ‘VISITED’ with ‘N’ rows and ‘M’ columns, where ‘VISITED[i][j]’ = 0 or 1, 0 representing the current cell being visited and 1 representing not visited.
• Iterate from ‘i’ = 0 to ‘N’ - 1,
• Iterate from ‘j’ = 0 toM’ - 1,
• If ‘GRID[i][j]’ == 1 && ‘VISITED[i][j]’ == 0,
• This means the current cell is an island that is not seen before.
• Run a ‘DFS’ function and mark all the connected lands as ‘VISITED’ that are connected to the cell (i,j).
• Increment 'NUMBEROFISLANDS' by 1.
• Append 'NUMBEROFISLANDS' to ‘ANS’.
6. Return the ‘ANS’ array.