File tree Expand file tree Collapse file tree 1 file changed +93
-0
lines changed
src/data-structure/5-graph Expand file tree Collapse file tree 1 file changed +93
-0
lines changed Original file line number Diff line number Diff line change 1+ // unidirectional graph check if route exist between 2 given nodes.
2+
3+ export class Graph {
4+ constructor ( ) {
5+ this . nodes = new Map ( ) ;
6+ }
7+
8+ addNode ( value ) {
9+ this . nodes . set ( value , [ ] ) ;
10+ }
11+
12+ addEdge ( origin , destination ) {
13+ this . nodes . has ( origin )
14+ ? this . nodes . get ( origin ) . push ( destination )
15+ : this . nodes . set ( origin , [ destination ] ) ;
16+ }
17+
18+ getEdges ( origin ) {
19+ return this . nodes . get ( origin ) || [ ] ;
20+ }
21+ }
22+
23+ const routes = [
24+ [ 8 , 5 ] ,
25+ [ 8 , 7 ] ,
26+ [ 7 , 11 ] ,
27+ [ 11 , 9 ] ,
28+ [ 5 , 3 ] ,
29+ [ 5 , 9 ] ,
30+ [ 5 , 10 ] ,
31+ [ 10 , 3 ] ,
32+ ] ;
33+
34+ const graph = new Graph ( ) ;
35+ routes . forEach ( ( r ) => graph . addEdge ( ...r ) ) ;
36+
37+ console . log ( graph ) ;
38+
39+ function bfs ( start , end ) {
40+ const queue = [ ] ;
41+ const visited = new Set ( ) ;
42+
43+ queue . push ( start ) ;
44+
45+ while ( queue . length ) {
46+ const node = queue . shift ( ) ;
47+ visit ( node , visited ) ;
48+
49+ if ( node === end ) {
50+ console . log ( 'Found ' , end ) ;
51+ break ;
52+ }
53+
54+ const children = graph . getEdges ( node ) ;
55+ queueChildren ( children , queue , visited ) ; 1
56+ }
57+ }
58+
59+ function visit ( node , visited ) {
60+ visited . add ( node ) ;
61+ console . log ( node ) ;
62+ }
63+
64+ function queueChildren ( children , queue , visited ) {
65+ children . forEach ( ( child ) => {
66+ if ( ! visited . has ( child ) ) {
67+ queue . push ( child ) ;
68+ }
69+ } ) ;
70+ }
71+
72+ bfs ( 8 , 9 ) ;
73+
74+ /** TESTING
75+ * end = 9, start = 8
76+ *
77+ * visted | queue | node
78+ * ===========================
79+ 8
80+ 8 5,7 8
81+ 8,5 3, 9, 10 5
82+ 8,5,7 3, 9, 10,11 7
83+ 8,5,7,3 9, 10,11 3
84+ 8,5,7,3,9 10,11 9
85+
86+ * output
87+ 8
88+ 5
89+ 7
90+ 3
91+ 9
92+ found 9
93+ */
You can’t perform that action at this time.
0 commit comments