@@ -3,22 +3,19 @@ class Graph {
33 this . adjacencyMap = { }
44 }
55
6- addVertex ( v ) {
7- this . adjacencyMap [ v ] = [ ]
6+ addVertex ( vertex ) {
7+ this . adjacencyMap [ vertex ] = [ ]
88 }
99
1010 containsVertex ( vertex ) {
1111 return typeof ( this . adjacencyMap [ vertex ] ) !== 'undefined'
1212 }
1313
14- addEdge ( v , w ) {
15- let result = false
16- if ( this . containsVertex ( v ) && this . containsVertex ( w ) ) {
17- this . adjacencyMap [ v ] . push ( w )
18- this . adjacencyMap [ w ] . push ( v )
19- result = true
14+ addEdge ( vertex1 , vertex2 ) {
15+ if ( this . containsVertex ( vertex1 ) && this . containsVertex ( vertex2 ) ) {
16+ this . adjacencyMap [ vertex1 ] . push ( vertex2 )
17+ this . adjacencyMap [ vertex2 ] . push ( vertex1 )
2018 }
21- return result
2219 }
2320
2421 printGraph ( output = value => console . log ( value ) ) {
@@ -35,7 +32,6 @@ class Graph {
3532
3633 /**
3734 * Prints the Breadth first traversal of the graph from source.
38- *
3935 * @param {number } source The source vertex to start BFS.
4036 */
4137 bfs ( source , output = value => console . log ( value ) ) {
@@ -55,6 +51,22 @@ class Graph {
5551 }
5652 }
5753 }
54+
55+ /**
56+ * Prints the Depth first traversal of the graph from source.
57+ * @param {number } source The source vertex to start DFS.
58+ */
59+ dfs ( source , visited = new Set ( ) , output = value => console . log ( value ) ) {
60+ if ( visited . has ( source ) ) { // visited
61+ return
62+ }
63+
64+ output ( `Visited node ${ source } ` )
65+ visited . add ( source )
66+ for ( const neighbour of this . adjacencyMap [ source ] ) {
67+ this . dfs ( neighbour , visited , output )
68+ }
69+ }
5870}
5971
6072const example = ( ) => {
@@ -69,11 +81,21 @@ const example = () => {
6981 g . addEdge ( 2 , 4 )
7082 g . addEdge ( 2 , 5 )
7183
84+ // Graph
85+ // 1 -> 2 3
86+ // 2 -> 1 4 5
87+ // 3 -> 1
88+ // 4 -> 2
89+ // 5 -> 2
90+
7291 // Printing the adjacency list
7392 // g.printGraph()
7493
7594 // Breadth first search at node 1
7695 g . bfs ( 1 )
96+
97+ // Depth first search at node 1
98+ g . dfs ( 1 )
7799}
78100
79101export { Graph , example }
0 commit comments