1
+ type StrIndexedObject = { [ index : string ] : Set < string > } ;
2
+
3
+
4
+ export default class SimpleGraph {
5
+ private numberOfNodes : number ;
6
+ private adjacentList : StrIndexedObject ;
7
+
8
+ constructor ( ) {
9
+ this . numberOfNodes = 0 ;
10
+ this . adjacentList = Object . create ( { } ) ;
11
+ }
12
+
13
+ public getNodeCount ( ) : number {
14
+ return this . numberOfNodes ;
15
+ }
16
+
17
+ public addVertex ( node : string ) {
18
+ this . adjacentList [ node ] = new Set < string > ( ) ;
19
+ ++ this . numberOfNodes ;
20
+ }
21
+
22
+ public addEdge ( node1 : string , node2 : string ) {
23
+ // Undirected, unweighted graph
24
+ this . adjacentList [ node1 ] . add ( node2 ) ;
25
+ this . adjacentList [ node2 ] . add ( node1 ) ;
26
+ }
27
+
28
+ public toString ( ) : string {
29
+ const allNodes = Object . keys ( this . adjacentList ) ;
30
+
31
+ let representation : string = "" ;
32
+
33
+ for ( let node of allNodes ) {
34
+ let nodeConnections = this . adjacentList [ node ] ;
35
+ let vertex ;
36
+ let count = 0 ;
37
+ let connections = " { " ;
38
+ for ( vertex of nodeConnections ) {
39
+ connections += vertex + ( count < nodeConnections . size - 1 ? ", " : " " ) ;
40
+ ++ count ;
41
+ }
42
+ representation += ( node + "-->" + connections + '}\n' ) ;
43
+ }
44
+ return representation ;
45
+ }
46
+ }
47
+
48
+ function printGraph ( graph : SimpleGraph ) {
49
+ console . log ( graph . toString ( ) ) ;
50
+ }
51
+
52
+ //---------------------------------------------------------------------
53
+ // ---------- MAIN PROGRAM ----------
54
+ //---------------------------------------------------------------------
55
+ if ( import . meta. main ) {
56
+
57
+ let simpleGraph = new SimpleGraph ( ) ;
58
+
59
+ simpleGraph . addVertex ( "0" ) ;
60
+ simpleGraph . addVertex ( "1" ) ;
61
+ simpleGraph . addVertex ( "2" ) ;
62
+ simpleGraph . addVertex ( "3" ) ;
63
+ simpleGraph . addVertex ( "4" ) ;
64
+ simpleGraph . addVertex ( "5" ) ;
65
+ simpleGraph . addVertex ( "6" ) ;
66
+ simpleGraph . addEdge ( "3" , "1" ) ;
67
+ simpleGraph . addEdge ( "3" , "4" ) ;
68
+ simpleGraph . addEdge ( "4" , "2" ) ;
69
+ simpleGraph . addEdge ( "4" , "5" ) ;
70
+ simpleGraph . addEdge ( "1" , "2" ) ;
71
+ simpleGraph . addEdge ( "1" , "0" ) ;
72
+ simpleGraph . addEdge ( "0" , "2" ) ;
73
+ simpleGraph . addEdge ( "6" , "5" ) ;
74
+
75
+ printGraph ( simpleGraph ) ;
76
+
77
+ // RUN: deno run Data-Structures/Graphs/Graph.ts
78
+ }
79
+
80
+ // --------------------------- Terminal Output: ---------------------------
81
+ // 0--> { 1, 2 }
82
+ // 1--> { 3, 2, 0 }
83
+ // 2--> { 4, 1, 0 }
84
+ // 3--> { 1, 4 }
85
+ // 4--> { 3, 2, 5 }
86
+ // 5--> { 4, 6 }
87
+ // 6--> { 5 }
0 commit comments