2
* @param {number[][]} stones5
var removeStones = function (stones) {6
const n = stones.length;7
// initial number of components(a.k.a island)10
//initial forest for union find11
let forest = new Array(n).fill(0).map((ele, index) => index);13
// recursively finding the root of rarget node15
if (forest[a] === a) {18
return find(forest[a]);21
// function for uniting two stones22
const union = (a, b) => {23
const rootA = find(a);24
const rootB = find(b);26
//connect their roots if currently they are not connected27
forest[rootA] = rootB;28
//subtract the number of islands by one since two islands are connected now33
for (let i = 0; i < stones.length - 1; i++) {34
for (let j = i + 1; j < stones.length; j++) {35
// if two stones are connected(i.e. share same row or column), unite them36
if (stones[i][0] === stones[j][0] || stones[i][1] === stones[j][1]) {42
// this is the most confusing part.43
// The number of stones can be removed is not equal to the number of islands.44
// e.g. we have two islands with total of 10 stores, each island will leave one extra stone after the45
// removal, therefore we can remove 10 - 2 = 8 stones in total46
return n - numComponents;