Skip to content

Instantly share code, notes, and snippets.

@jmcguirk
Created October 6, 2014 22:21
Show Gist options
  • Save jmcguirk/2dcfa3aa3511e6644ba4 to your computer and use it in GitHub Desktop.
Save jmcguirk/2dcfa3aa3511e6644ba4 to your computer and use it in GitHub Desktop.
var vertices = [];
var edges = [];
vertices.push("A");
vertices.push("B");
vertices.push("C");
vertices.push("D");
vertices.push("E");
edges.push(["A", "B"]);
edges.push(["A", "C"]);
edges.push(["B", "D"]);
edges.push(["D", "C"]);
function getChildren(vertex){
var result = [];
for(var i = 0; i < edges.length; i++){
if(edges[i][0] == vertex){
result.push(edges[i][1]);
}
if(edges[i][1] == vertex){ // JSM - remove this if you want it to be directed graph
result.push(edges[i][0]);
}
}
return result;
}
function getUnvisitedChildren(vertex, visitList){
var result = [];
var children = getChildren(vertex);
for(var j = 0; j < children.length; j++){
if(visitList.indexOf(children[j]) < 0){
result.push(children[j]);
}
}
return result;
}
var visitList = [];
function getUnreachableNodes(root){
var queue = [];
var visitList = [];
queue.push(root);
while(queue.length > 0){
var next = queue.shift();
if(visitList.indexOf(next) < 0){
visitList.push(next);
queue = queue.concat(getUnvisitedChildren(next, visitList));
}
}
var missingList = [];
for(var i = 0; i < vertices.length; i++){
if(visitList.indexOf(vertices[i]) < 0){
missingList.push(vertices[i]);
}
}
return missingList;
}
function testConnectivity(root){
var nodes = getUnreachableNodes(root);
if(nodes.length > 0){
console.log("Graph is NOT fully connected");
for(var i = 0; i < nodes.length; i++){
console.log(nodes[i] + " could not be reached");
}
} else{
console.log("Graph is fully connected")
}
}
testConnectivity("A");
testConnectivity("E");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment