Created
April 15, 2019 16:37
-
-
Save AdvaithD/128d1176260891f56ae0fe3069d959a3 to your computer and use it in GitHub Desktop.
Graph
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Graph { | |
constructor() { | |
this.adjacencyList = new Map(); | |
} | |
addVertex(nodeVal) { | |
this.adjacencyList.set(nodeVal, []); | |
} | |
addEdge(src, dest) { | |
this.adjacencyList.get(src).push(dest); | |
this.adjacencyList.get(dest).push(src); | |
} | |
removeVertex(val) { | |
if (this.adjacencyList.get(val)) { | |
this.adjacencyList.delete(val); | |
} | |
this.adjacencyList.forEach((vertex) => { | |
const neighborIdx = vertex.indexOf(val); | |
if (neighborIdx >= 0) { | |
vertex.splice(neighborIdx, 1); | |
} | |
}); | |
} | |
removeEdge(src, dest) { | |
const srcDestIdx = this.adjacencyList.get(src).indexOf(dest); | |
this.adjacencyList.get(src).splice(srcDestIdx, 1); | |
const destSrcIdx = this.adjacencyList.get(dest).indexOf(src); | |
this.adjacencyList.get(dest).splice(destSrcIdx, 1); | |
} | |
printNeighbors() { | |
const result = []; | |
for (let vertex of this.adjacencyList.keys()) { | |
const neighbors = []; | |
neighbors.push(`${vertex}:`); | |
this.adjacencyList.get(vertex).forEach((neighbor) => { | |
neighbors.push(neighbor); | |
}); | |
result.push(neighbors.join(' ')); | |
} | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment