File tree Expand file tree Collapse file tree 1 file changed +81
-0
lines changed Expand file tree Collapse file tree 1 file changed +81
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Graph {
2
+ constructor ( ) {
3
+ this . adjacencyList = { } ;
4
+ }
5
+
6
+ addVertex ( vtx ) {
7
+ if ( ! this . adjacencyList [ vtx ] ) {
8
+ this . adjacencyList [ vtx ] = [ ] ;
9
+ return true ;
10
+ }
11
+ return false ;
12
+ }
13
+
14
+ addEdge ( vtx1 , vtx2 ) {
15
+ if ( this . adjacencyList [ vtx1 ] && this . adjacencyList [ vtx2 ] ) {
16
+ this . adjacencyList [ vtx1 ] . push ( vtx2 ) ;
17
+ this . adjacencyList [ vtx2 ] . push ( vtx1 ) ;
18
+ return true ;
19
+ }
20
+ return false ;
21
+ }
22
+
23
+ removeEdge ( vtx1 , vtx2 ) {
24
+ if ( this . adjacencyList [ vtx1 ] && this . adjacencyList [ vtx2 ] ) {
25
+ this . adjacencyList [ vtx1 ] = this . adjacencyList [ vtx2 ] . filter (
26
+ ( v ) => v !== vtx2
27
+ ) ;
28
+
29
+ this . adjacencyList [ vtx2 ] = this . adjacencyList [ vtx2 ] . filter (
30
+ ( v ) => v !== vtx1
31
+ ) ;
32
+ return true ;
33
+ }
34
+ return false ;
35
+ }
36
+
37
+ removeVertex ( vtx ) {
38
+ if ( ! this . adjacencyList [ vtx ] ) return undefined ;
39
+
40
+ for ( let neighbor of this . adjacencyList [ vtx ] ) {
41
+ this . adjacencyList [ neighbor ] = this . adjacencyList [ neighbor ] . filter (
42
+ ( v ) => v !== vtx
43
+ ) ;
44
+ }
45
+
46
+ delete this . adjacencyList [ vtx ] ;
47
+ return this ;
48
+ }
49
+ }
50
+
51
+ let g = new Graph ( ) ;
52
+ // ----------------
53
+ // g.addVertex("A");
54
+ // g.addVertex("B");
55
+ // g.addEdge("A", "B");
56
+ // ----------------
57
+
58
+ // ----------------
59
+ // g.addVertex("A");
60
+ // g.addVertex("B");
61
+ // g.addVertex("C");
62
+ // g.addEdge("A", "B");
63
+ // g.addEdge("B", "C");
64
+ // g.addEdge("C", "A");
65
+ // console.log(g);
66
+ // g.removeEdge("A", "B");
67
+ // console.log(g);
68
+ // ----------------
69
+
70
+ g . addVertex ( "A" ) ;
71
+ g . addVertex ( "B" ) ;
72
+ g . addVertex ( "C" ) ;
73
+ g . addVertex ( "D" ) ;
74
+ g . addEdge ( "A" , "B" ) ;
75
+ g . addEdge ( "A" , "C" ) ;
76
+ g . addEdge ( "A" , "D" ) ;
77
+ g . addEdge ( "B" , "D" ) ;
78
+ g . addEdge ( "C" , "D" ) ;
79
+ console . log ( g ) ;
80
+ g . removeVertex ( "D" ) ;
81
+ console . log ( g ) ;
You can’t perform that action at this time.
0 commit comments