Skip to content

Graph #850

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Nov 27, 2021
Merged

Graph #850

Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 32 additions & 10 deletions Data-Structures/Graph/Graph.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,19 @@ class Graph {
this.adjacencyMap = {}
}

addVertex (v) {
this.adjacencyMap[v] = []
addVertex (vertex) {
this.adjacencyMap[vertex] = []
}

containsVertex (vertex) {
return typeof (this.adjacencyMap[vertex]) !== 'undefined'
}

addEdge (v, w) {
let result = false
if (this.containsVertex(v) && this.containsVertex(w)) {
this.adjacencyMap[v].push(w)
this.adjacencyMap[w].push(v)
result = true
addEdge (vertex1, vertex2) {
if (this.containsVertex(vertex1) && this.containsVertex(vertex2)) {
this.adjacencyMap[vertex1].push(vertex2)
this.adjacencyMap[vertex2].push(vertex1)
}
return result
}

printGraph (output = value => console.log(value)) {
Expand All @@ -35,7 +32,6 @@ class Graph {

/**
* Prints the Breadth first traversal of the graph from source.
*
* @param {number} source The source vertex to start BFS.
*/
bfs (source, output = value => console.log(value)) {
Expand All @@ -55,6 +51,22 @@ class Graph {
}
}
}

/**
* Prints the Depth first traversal of the graph from source.
* @param {number} source The source vertex to start DFS.
*/
dfs (source, visited = new Set(), output = value => console.log(value)) {
if (visited.has(source)) { // visited
return
}

output(`Visited node ${source}`)
visited.add(source)
for (const neighbour of this.adjacencyMap[source]) {
this.dfs(neighbour, visited, output)
}
}
}

const example = () => {
Expand All @@ -69,11 +81,21 @@ const example = () => {
g.addEdge(2, 4)
g.addEdge(2, 5)

// Graph
// 1 -> 2 3
// 2 -> 1 4 5
// 3 -> 1
// 4 -> 2
// 5 -> 2

// Printing the adjacency list
// g.printGraph()

// Breadth first search at node 1
g.bfs(1)

// Depth first search at node 1
g.dfs(1)
}

export { Graph, example }