I have understood what I have to do in the problem. I implemented the solution for the first subtask, it went well. But for the other subtasks, I am not able to understand the DSU part. I found out the length of each component having same integer from the grid using BFS. So far, I know that there are different sets (here components) and we can merge them and the index of each component will be representing the set (component). But, how are we finding if the components are adjacent? Also, how are we managing the situation where we need to merge an already connected component to the next component.
I went through the Author's solution but I am not able to understand what he did after finding the length of all components. Can anyone help me here understand the last part.
Here is the solution I prepared till now: https://ideone.com/fzVkPV