mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-05 00:01:37 +08:00

* chore: Switch to Node 20 + Vitest * chore: migrate to vitest mock functions * chore: code style (switch to prettier) * test: re-enable long-running test Seems the switch to Node 20 and Vitest has vastly improved the code's and / or the test's runtime! see #1193 * chore: code style * chore: fix failing tests * Updated Documentation in README.md * Update contribution guidelines to state usage of Prettier * fix: set prettier printWidth back to 80 * chore: apply updated code style automatically * fix: set prettier line endings to lf again * chore: apply updated code style automatically --------- Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Co-authored-by: Lars Müller <34514239+appgurueu@users.noreply.github.com>
63 lines
1.3 KiB
JavaScript
63 lines
1.3 KiB
JavaScript
// create a graph class
|
|
class Graph {
|
|
// defining vertex array and
|
|
// adjacent list
|
|
constructor(noOfVertices) {
|
|
this.noOfVertices = noOfVertices
|
|
this.AdjList = new Map()
|
|
}
|
|
|
|
// functions to be implemented
|
|
|
|
// addVertex(v)
|
|
// addEdge(v, w)
|
|
// printGraph()
|
|
|
|
// bfs(v)
|
|
// dfs(v)
|
|
|
|
// add vertex to the graph
|
|
addVertex(v) {
|
|
// initialize the adjacent list with a
|
|
// null array
|
|
|
|
this.AdjList.set(v, [])
|
|
}
|
|
|
|
// add edge to the graph
|
|
addEdge(v, w) {
|
|
// get the list for vertex v and put the
|
|
// vertex w denoting edge between v and w
|
|
this.AdjList.get(v).push(w)
|
|
|
|
// Since graph is undirected,
|
|
// add an edge from w to v also
|
|
this.AdjList.get(w).push(v)
|
|
}
|
|
|
|
// Prints the vertex and adjacency list
|
|
printGraph(output = (value) => console.log(value)) {
|
|
// get all the vertices
|
|
const getKeys = this.AdjList.keys()
|
|
|
|
// iterate over the vertices
|
|
for (const i of getKeys) {
|
|
// get the corresponding adjacency list
|
|
// for the vertex
|
|
const getValues = this.AdjList.get(i)
|
|
let conc = ''
|
|
|
|
// iterate over the adjacency list
|
|
// concatenate the values into a string
|
|
for (const j of getValues) {
|
|
conc += j + ' '
|
|
}
|
|
|
|
// print the vertex and its adjacency list
|
|
output(i + ' -> ' + conc)
|
|
}
|
|
}
|
|
}
|
|
|
|
export { Graph }
|