Skip to content

Instantly share code, notes, and snippets.

@samteb
Created July 2, 2019 04:46
Show Gist options
  • Save samteb/bef2d895df8b4b51dab30455f34b5b5d to your computer and use it in GitHub Desktop.
Save samteb/bef2d895df8b4b51dab30455f34b5b5d to your computer and use it in GitHub Desktop.
class Graph {
constructor () {
this.adjacencyList = {};
}
addVertex (vertex) {
if (!this.adjacencyList[vertex]) this.adjacencyList[vertex] = [];
}
addEdge (vertex1, vertex2) {
if (this.adjacencyList[vertex1] && this.adjacencyList[vertex2]) {
this.adjacencyList[vertex1].push(vertex2);
this.adjacencyList[vertex2].push(vertex1);
}
}
removeEdge (vertex1, vertex2) {
if (this.adjacencyList[vertex1] && this.adjacencyList[vertex2]) {
this.adjacencyList[vertex1] = this.adjacencyList[vertex1].filter(v => v !== vertex2);
this.adjacencyList[vertex2] = this.adjacencyList[vertex2].filter(v => v !== vertex1);
}
}
removeVertex (vertex) {
if (this.adjacencyList[vertex]) {
while (this.adjacencyList[vertex].length) {
const adjacentVertex = this.adjacencyList[vertex].pop();
this.removeEdge(vertex, adjacentVertex);
}
delete this.adjacencyList[vertex];
}
}
depthFirstSearchRecursive (vertex) {
const result = [];
const visited = {};
const adjacencyList = this.adjacencyList;
function helper (v) {
if (!v) return null;
result.push(v);
visited[v] = true;
adjacencyList[v].forEach(neighbor => {
if (!visited[neighbor]) {
return helper(neighbor);
}
});
}
helper(vertex);
return result;
}
depthFirstSearchIterative (vertex) {
const result = [];
const visited = {};
const stack = [ vertex ];
visited[vertex] = true;
while (stack.length) {
const vertex = stack.pop();
result.push(vertex);
this.adjacencyList[vertex].forEach(neighbor => {
if (!visited[neighbor]) {
visited[neighbor] = true;
stack.push(neighbor);
}
});
}
return result;
}
breadthFirstSearch (vertex) {
const result = [];
const visited = {};
const queue = [ vertex ];
visited[vertex] = true;
while (queue.length) {
const vertex = queue.shift();
result.push(vertex);
this.adjacencyList[vertex].forEach(neighbor => {
if (!visited[neighbor]) {
visited[neighbor] = true;
queue.push(neighbor);
}
});
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment