11const Node = require ( './node' ) ;
2+ const Stack = require ( '../stacks/stack' ) ;
3+ const Queue = require ( '../queues/queue' ) ;
24
35/**
46 * Graph that uses an adjacent list
@@ -49,6 +51,13 @@ class Graph {
4951 return this . nodes . delete ( value ) ;
5052 }
5153
54+ /**
55+ * Create a connection between source node and target node.
56+ * If the graph is undirected it will also create the conneciton from target to destination.
57+ * If the nodes doesn't exist then it will create them on the fly
58+ * @param {any } source
59+ * @param {any } target
60+ */
5261 addEdge ( source , target ) {
5362 const sourceNode = this . addVertex ( source ) ;
5463 const targetNode = this . addVertex ( target ) ;
@@ -62,6 +71,12 @@ class Graph {
6271 return [ sourceNode , targetNode ] ;
6372 }
6473
74+ /**
75+ * Remove connection between source node and target.
76+ * If the graph is undirected it will also remove the conneciton from target to destination.
77+ * @param {any } source
78+ * @param {any } target
79+ */
6580 removeEdge ( source , target ) {
6681 const sourceNode = this . nodes . get ( source ) ;
6782 const targetNode = this . nodes . get ( target ) ;
@@ -76,6 +91,22 @@ class Graph {
7691
7792 return [ sourceNode , targetNode ] ;
7893 }
94+
95+ * dfs ( first ) {
96+ const visited = new Map ( ) ;
97+ const visitList = new Stack ( ) ;
98+
99+ visitList . add ( first ) ;
100+
101+ while ( ! visitList . isEmpty ( ) ) {
102+ const node = visitList . remove ( ) ;
103+ if ( node && ! visited . has ( node ) ) {
104+ yield node ;
105+ visited . set ( node ) ;
106+ node . getAdjacents ( ) . forEach ( adj => visitList . add ( adj ) ) ;
107+ }
108+ }
109+ }
79110}
80111
81112Graph . UNDIRECTED = Symbol ( 'directed graph' ) ; // one-way edges
0 commit comments