Skip to content

Instantly share code, notes, and snippets.

@gserrano
Last active January 19, 2021 17:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gserrano/54be22489f1359084adec5ae9e54b0c5 to your computer and use it in GitHub Desktop.
Save gserrano/54be22489f1359084adec5ae9e54b0c5 to your computer and use it in GitHub Desktop.
class Graph {
//VERTICES: array of vertices
//EGDES: array of edges, each edge is a 2 item array (V1, V2)
constructor(VERTICES,EDGES){
this.G = new Map();
this.VERTICES = VERTICES;
if(VERTICES)
VERTICES.forEach((V) => this.addVertex(V));
if(VERTICES && EDGES){
EDGES.forEach((V) => {
this.addEdge(V[0], V[1])
});
}
}
addVertex(V){
this.G.set(V, new Set());
}
addEdge(V1, V2){
this.G.get(V1).add(V2);
this.G.get(V2).add(V1);
}
//check is exists a continuous path, starting at the smaller vertex and ending on the last going through all nodes
checkContinuousPath(){
const LV = this.VERTICES.length;
const sorted = this.VERTICES.slice().sort();
for(let i = 0; i < LV-1; i++){
if(!this.G.get(sorted[i]).has(sorted[i+1])){
console.log(`missing edge from ${sorted[i]} to ${sorted[i+1]}`);
return false;
}
console.log(`has edge from ${sorted[i]} to ${sorted[i+1]}`);
}
return true;
}
showMap(){
console.log(this.G)
}
bfs(start,end){
console.log(`breadth first search from ${start} to ${end}`);
const queue = [start];
const visited = new Set();
while(queue.length > 0){
const node = queue.shift();
const childs = this.G.get(node);
visited.add(node);
console.log(`checking ${node}`);
for(let dest of childs){
if(dest === end){
console.log(`found route to ${end}`);
}
if(!visited.has(dest)){
visited.add(dest)
queue.push(dest);
}
}
}
}
dfs(start,end,visited = new Set()){
console.log(`deep first search from ${start} to ${end} - #${visited.size}`)
visited.add(start);
const childs = this.G.get(start);
for(let dest of childs){
if(dest === end){
console.log(`found route to ${end}`);
return;
}
if(!visited.has(dest)){
this.dfs(dest,end,visited);
}
}
}
}
example = new Graph([1,2,3,4,5], [[1,2],[2,3],[3,4],[4,5]]);
example.showMap();
example.bfs(1,3);
example.dfs(1,3);
console.log(example.checkContinuousPath());
console.log('---------------')
console.log('---------------')
example = new Graph([1,2,3,4,5], [[1,2],[3,4],[4,5],[2,5]]);
example.showMap();
example.bfs(1,3);
example.dfs(1,3);
console.log(example.checkContinuousPath()); //false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment