2020-05-05 16:58:57 +05:30
|
|
|
// create a graph class
|
|
|
|
|
class Graph {
|
|
|
|
|
// defining vertex array and
|
|
|
|
|
// adjacent list
|
2023-10-03 23:08:19 +02:00
|
|
|
constructor(noOfVertices) {
|
2020-05-05 16:58:57 +05:30
|
|
|
this.noOfVertices = noOfVertices
|
|
|
|
|
this.AdjList = new Map()
|
|
|
|
|
}
|
2020-04-17 22:10:40 +02:00
|
|
|
|
2020-05-05 16:58:57 +05:30
|
|
|
// functions to be implemented
|
2020-04-17 22:10:40 +02:00
|
|
|
|
2020-05-05 16:58:57 +05:30
|
|
|
// addVertex(v)
|
|
|
|
|
// addEdge(v, w)
|
|
|
|
|
// printGraph()
|
2020-05-03 09:05:12 +02:00
|
|
|
|
2020-05-05 16:58:57 +05:30
|
|
|
// bfs(v)
|
|
|
|
|
// dfs(v)
|
2020-05-03 09:05:12 +02:00
|
|
|
|
2020-05-05 16:58:57 +05:30
|
|
|
// add vertex to the graph
|
2023-10-03 23:08:19 +02:00
|
|
|
addVertex(v) {
|
2020-05-05 16:58:57 +05:30
|
|
|
// initialize the adjacent list with a
|
|
|
|
|
// null array
|
|
|
|
|
|
|
|
|
|
this.AdjList.set(v, [])
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// add edge to the graph
|
2023-10-03 23:08:19 +02:00
|
|
|
addEdge(v, w) {
|
2020-05-05 16:58:57 +05:30
|
|
|
// 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)
|
|
|
|
|
}
|
2020-04-17 22:10:40 +02:00
|
|
|
|
2020-05-05 16:58:57 +05:30
|
|
|
// Prints the vertex and adjacency list
|
2023-10-03 23:08:19 +02:00
|
|
|
printGraph(output = (value) => console.log(value)) {
|
2020-05-05 16:58:57 +05:30
|
|
|
// get all the vertices
|
|
|
|
|
const getKeys = this.AdjList.keys()
|
2020-05-03 09:05:12 +02:00
|
|
|
|
2020-05-05 16:58:57 +05:30
|
|
|
// iterate over the vertices
|
|
|
|
|
for (const i of getKeys) {
|
2023-09-19 16:40:32 +05:30
|
|
|
// get the corresponding adjacency list
|
2020-05-05 16:58:57 +05:30
|
|
|
// 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
|
2021-10-11 14:23:24 +02:00
|
|
|
output(i + ' -> ' + conc)
|
2020-05-05 16:58:57 +05:30
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2021-10-11 14:23:24 +02:00
|
|
|
export { Graph }
|