Skip to content

Commit

Permalink
merge: Graph (TheAlgorithms#850)
Browse files Browse the repository at this point in the history
* Modify Graph bfs method

* add dfs in graph
  • Loading branch information
Yatin-kathuria authored Nov 27, 2021
1 parent 061218b commit c33b19a
Showing 1 changed file with 32 additions and 10 deletions.
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 }

0 comments on commit c33b19a

Please sign in to comment.