Created
March 13, 2024 19:45
-
-
Save 32teeth/a370aa9c9ae928033ab5109cd7d51574 to your computer and use it in GitHub Desktop.
Entity Relationship
This file contains 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 Queue { | |
constructor() { | |
this.elements = []; | |
} | |
enqueue = (e) => this.elements.push(e); | |
dequeue = (e) => this.elements.shift(); | |
isEmpty = () => this.elements.length === 0; | |
peek = () => !this.isEmpty() ? this.elements[0] : undefined; | |
length = () => this.elements.length; | |
dump = () => this.elements; | |
} | |
class Graph { | |
/** | |
* | |
* @param {interger} v - number of vertices | |
*/ | |
constructor(numberOfVertices) { | |
this.numberOfVertices = numberOfVertices; | |
this.adjNodes = new Map(); | |
} | |
/** | |
* class methods | |
*/ | |
/** | |
* Add Vertex | |
*/ | |
addVertex = (vertex) => this.adjNodes.set(vertex, []) | |
/** | |
* Add Edge | |
*/ | |
addEdge = (vertex, edge) => { | |
this.adjNodes.get(vertex).push(edge); | |
// if the graph is undirected | |
this.adjNodes.get(edge).push(vertex); | |
} | |
/** | |
* Print Graph | |
*/ | |
printGraph = () => { | |
let graph = ''; | |
this.adjNodes.forEach((edges, vertex) => { | |
graph += ` | |
${vertex} -> ${edges.join(' ')} | |
` | |
}) | |
return graph; | |
} | |
/** | |
* Breadth First Search | |
*/ | |
breadthFirstSearch = (node) => { | |
let visited = {}; | |
let Q = new Queue(); | |
visited[node] = true; | |
Q.enqueue(node); | |
while (!Q.isEmpty()) { | |
node = Q.dequeue(); | |
let nodes = this.adjNodes.get(node); | |
nodes.forEach((node) => { | |
if (!nodes?.[node]) { | |
visited[node] = true; | |
Q.enqueue[node] | |
} | |
}) | |
} | |
return visited; | |
} | |
/** | |
* Depth First Search | |
*/ | |
depthFirstSearch = (node) => { | |
let visited = {}; | |
this.depthFirstSearchUtil(node, visited); | |
return visited; | |
} | |
depthFirstSearchUtil = (vertex, visited) => { | |
visited[vertex] = true; | |
let neighbours = this.adjNodes.get(vertex); | |
for (let i in neighbours) { | |
let node = neighbours[i]; | |
if (!visited[node]) { | |
this.depthFirstSearchUtil(node, visited); | |
} | |
} | |
} | |
} | |
const G = new Graph(8); | |
['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'CAFE'].forEach((v) => { | |
G.addVertex(v) | |
}) | |
// adding edges | |
G.addEdge('B', 'C'); | |
G.addEdge('D', 'B'); | |
G.addEdge('A', 'D'); | |
G.addEdge('E', 'F'); | |
G.addEdge('F', 'G'); | |
// DICE | |
G.addEdge('CAFE', 'D'); | |
G.addEdge('CAFE', 'I'); | |
G.addEdge('CAFE', 'C'); | |
G.addEdge('CAFE', 'E'); | |
console.log(G.printGraph()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment