LeetCode – Most Stones Removed with Same Row or Column (Java)

The easiest solution for this problem is the union-find. The number of island problem can help understand how union-find works.

The basic idea is that we use a disjoint set to track each component. Whenever two stones can be connected, the number of islands decrease one. The final result, the number of movement, is the total number of stones - the number of islands.

Java Solution

class Solution {
    int[] root = new int[1000]; //value is index
    int[] size = new int[1000];
    int result = 0;
 
    public int removeStones(int[][] stones) {
        result = stones.length;
        for(int i=0; i<stones.length; i++){
            root[i]=i;    
        }
 
        for(int i=0; i<stones.length; i++){
            for(int j=i+1; j<stones.length; j++){
                if(stones[i][0]==stones[j][0] || stones[i][1]==stones[j][1]){
                    union(i, j);
                }
            }
        }
 
        return stones.length-result;
    }
 
    public void union(int i, int j){
        int rootI = getRoot(i);
        int rootJ = getRoot(j);
 
        if(rootI==rootJ){
            return;
        }
 
        if (size[rootI] <= size[rootJ]) {
            root[rootI]=rootJ;
            size[rootJ]++;
        }else{
            root[rootJ]=rootI;
            size[rootI]++;
        }
 
        result--;
    }
 
    public int getRoot(int i){
        while(i!=root[i]){
            i=root[i];
        }
 
        return i;
    }
}
Category >> Algorithms  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>