/**
* @param {number[][]} M
* @return {number}
*/
var findCircleNum = function(M) {
let list = [];
let toRemoveIndex = new Set();
function addToList(ele1, ele2){
let handledIndex = -1;
for(let i = 0; i < list.length; ++i){
let set = list[i];
if(set.has(ele1) || set.has(ele2)){
if(handledIndex > -1){ // 之前已经有set处理过,说明有2个set可以融合。
let s = new Set([...set, ...list[handledIndex]]);
toRemoveIndex.add(i);
list.splice(handledIndex, 1, s);
}
else{
set.add(ele1);
set.add(ele2);
handledIndex = i;
}
}
}
if(handledIndex < 0){
list.push(new Set([ele1, ele2]));
}
}
if(!M.length){
return 0;
}
if(M.length === 1){
return 1;
}
let len = M.length;
for(let i = len - 1; i >= 0; --i){
for(let j = 0; j <= i; ++j){
if(M[i][j] === 1){
addToList(i, j);
}
}
}
return list.length - toRemoveIndex.size;
};
复制代码
转载于:https://juejin.im/post/5b1a47186fb9a01e8c5fd091