Number of islands II

Graphs Hard Problems II Hard
  • This problem is a perfect representation of how geographical information systems (GIS) work
  • In GIS software, they constantly deal with similar situations
  • Land mass configuration, changes over time, and pinpointing particular areas on the maps are an everyday task for them
  • Watershed modeling, environmental changes, town planning, or even video games that deal with terrain generation could use an algorithm that solves this problem

Given n, m denoting the row and column of the 2D matrix, and an array A of size k denoting the number of operations. Matrix elements are 0 if there is water or 1 if there is land. Originally, the 2D matrix is all 0 which means there is no land in the matrix. The array has k operator(s) and each operator has two integers A[i][0], A[i][1] means that you can change the cell matrix[A[i][0]][A[i][1]] from sea to island. Return how many islands are there in the matrix after each operation.


The answer array will be of size k.

Examples:

Input: n = 4, m = 5, k = 4, A = [[1,1],[0,1],[3,3],[3,4]] 

Output: [1, 1, 2, 2]

Explanation: The following illustration is the representation of the operation:

Input: n = 4, m = 5, k = 12, A = [[0,0],[0,0],[1,1],[1,0],[0,1],[0,3],[1,3],[0,4], [3,2], [2,2],[1,2], [0,2]] 

Output: [1, 1, 2, 1, 1, 2, 2, 2, 3, 3, 1, 1] 

Explanation: If we follow the process like in example 1, we will get the above result.

Input: n = 2, m = 2, k = 4, A = [[0,0],[0,1],[1,0],[1,1]] 

Constraints

  •   1 <= n, m <= 1000
  •   1 <= k <= 104
  •   0 <= A[i][0] < n
  •   0 <= A[i][1] < m

Hints

  • The optimal way to track connected components is using Disjoint Set Union (DSU) (also called Union-Find).
  • "Treat each land cell as a node in a disjoint set. When a cell (r, c) is converted into land. It initially forms a new island. Check its four neighbors (up, down, left, right). If any neighbor is also land (1), merge them using Union-Find. Step 3: After each operation, return the current number of distinct islands"

Company Tags

Oracle Visa Byju's Zomato Walmart Wayfair Stripe Zynga PayPal Dropbox Splunk McKinsey & Company Roblox Rockstar Games Etsy Red Hat JPMorgan Chase Reddit Uber Siemens Healthineers Activision Blizzard American Express IBM Riot Games Swiggy Google Microsoft Amazon Meta Apple Netflix Adobe