I am trying to solve problem in leetcode: https://leetcode.com/problems/redundant-connection/description/ *finding redundant connection in undirected graph
And now I am writing a solution, inpired by Kruskal's algorithm: https://en.wikipedia.org/wiki/Disjoint-set_data_structure#/media/File:UnionFindKruskalDemo.gif
In short: I just add vertices in sets if I find a pair, when both vertices exist in set then it is an additional edge...
var findRedundantConnection = function(edges) {
let additionals = [];
let sets = [];
for (let i = 0; i < edges.length; i++) {
//find connections of each vertices in edge
let check_0_indexes = [];
let check_1_indexes = [];
for (let j = 0; j < sets.length; j++) {
if (sets[j]&&sets[j].includes(edges[i][0])) { //if vertices exist in sets
check_0_indexes.push(j);
} else if (sets[j]&&sets[j].includes(edges[i][1])) {
check_1_indexes.push(j);
}
}
//add to sets (but if not an additional, if additional then add to additionals)
check_0_indexes.map(el=>{
if(sets[el].includes(edges[i][1])){ //check first vertice: if pair exist in set
additionals.push(edges[i]);
} else {
sets[el].push(edges[i][1]);
}
});
check_1_indexes.map(el=>{
if(sets[el].includes(edges[i][0])){
additionals.push(edges[i]); //check second vertice: if pair exist in set
} else {
sets[el].push(edges[i][0]);
}
});
if(!check_0_indexes.length&&!check_1_indexes.length){
//if both vertices not in sets
sets.push([]); //create new set and add vertices
sets[sets.length-1].push(edges[i][0]);
sets[sets.length-1].push(edges[i][1]);
}
}
return additionals.pop();
};
*JavaScript
But in this case:
edges = [[3,7],[1,4],[2,8],[1,6],[7,9],[6,10],[1,7],[2,3],[8,9],[5,9]]
I do not know how to catch loop ( (8,9) and (7,9) )
Any ideas about it?