data-structure-typed 1.18.0 → 1.18.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (290) hide show
  1. package/README.md +193 -66
  2. package/backup/recursive-type/src/assets/complexities-diff.jpg +0 -0
  3. package/backup/recursive-type/src/assets/data-structure-complexities.jpg +0 -0
  4. package/backup/recursive-type/src/assets/logo.png +0 -0
  5. package/backup/recursive-type/src/assets/overview-diagram-of-data-structures.png +0 -0
  6. package/backup/recursive-type/src/data-structures/binary-tree/aa-tree.ts +3 -0
  7. package/backup/recursive-type/src/data-structures/binary-tree/avl-tree.ts +288 -0
  8. package/backup/recursive-type/src/data-structures/binary-tree/b-tree.ts +3 -0
  9. package/backup/recursive-type/src/data-structures/binary-tree/binary-indexed-tree.ts +78 -0
  10. package/backup/recursive-type/src/data-structures/binary-tree/binary-tree.ts +1502 -0
  11. package/backup/recursive-type/src/data-structures/binary-tree/bst.ts +503 -0
  12. package/backup/recursive-type/src/data-structures/binary-tree/diagrams/avl-tree-inserting.gif +0 -0
  13. package/backup/recursive-type/src/data-structures/binary-tree/diagrams/bst-rotation.gif +0 -0
  14. package/backup/recursive-type/src/data-structures/binary-tree/diagrams/segment-tree.png +0 -0
  15. package/backup/recursive-type/src/data-structures/binary-tree/index.ts +11 -0
  16. package/backup/recursive-type/src/data-structures/binary-tree/rb-tree.ts +110 -0
  17. package/backup/recursive-type/src/data-structures/binary-tree/segment-tree.ts +243 -0
  18. package/backup/recursive-type/src/data-structures/binary-tree/splay-tree.ts +3 -0
  19. package/backup/recursive-type/src/data-structures/binary-tree/tree-multiset.ts +55 -0
  20. package/backup/recursive-type/src/data-structures/binary-tree/two-three-tree.ts +3 -0
  21. package/backup/recursive-type/src/data-structures/diagrams/README.md +5 -0
  22. package/backup/recursive-type/src/data-structures/graph/abstract-graph.ts +985 -0
  23. package/backup/recursive-type/src/data-structures/graph/diagrams/adjacency-list-pros-cons.jpg +0 -0
  24. package/backup/recursive-type/src/data-structures/graph/diagrams/adjacency-list.jpg +0 -0
  25. package/backup/recursive-type/src/data-structures/graph/diagrams/adjacency-matrix-pros-cons.jpg +0 -0
  26. package/backup/recursive-type/src/data-structures/graph/diagrams/adjacency-matrix.jpg +0 -0
  27. package/backup/recursive-type/src/data-structures/graph/diagrams/dfs-can-do.jpg +0 -0
  28. package/backup/recursive-type/src/data-structures/graph/diagrams/edge-list-pros-cons.jpg +0 -0
  29. package/backup/recursive-type/src/data-structures/graph/diagrams/edge-list.jpg +0 -0
  30. package/backup/recursive-type/src/data-structures/graph/diagrams/max-flow.jpg +0 -0
  31. package/backup/recursive-type/src/data-structures/graph/diagrams/mst.jpg +0 -0
  32. package/backup/recursive-type/src/data-structures/graph/diagrams/tarjan-articulation-point-bridge.png +0 -0
  33. package/backup/recursive-type/src/data-structures/graph/diagrams/tarjan-complicate-simple.png +0 -0
  34. package/backup/recursive-type/src/data-structures/graph/diagrams/tarjan-strongly-connected-component.png +0 -0
  35. package/backup/recursive-type/src/data-structures/graph/diagrams/tarjan.mp4 +0 -0
  36. package/backup/recursive-type/src/data-structures/graph/diagrams/tarjan.webp +0 -0
  37. package/backup/recursive-type/src/data-structures/graph/directed-graph.ts +478 -0
  38. package/backup/recursive-type/src/data-structures/graph/index.ts +3 -0
  39. package/backup/recursive-type/src/data-structures/graph/undirected-graph.ts +293 -0
  40. package/backup/recursive-type/src/data-structures/hash/coordinate-map.ts +67 -0
  41. package/backup/recursive-type/src/data-structures/hash/coordinate-set.ts +56 -0
  42. package/backup/recursive-type/src/data-structures/hash/hash-table.ts +3 -0
  43. package/backup/recursive-type/src/data-structures/hash/index.ts +6 -0
  44. package/backup/recursive-type/src/data-structures/hash/pair.ts +3 -0
  45. package/backup/recursive-type/src/data-structures/hash/tree-map.ts +3 -0
  46. package/backup/recursive-type/src/data-structures/hash/tree-set.ts +3 -0
  47. package/backup/recursive-type/src/data-structures/heap/heap.ts +176 -0
  48. package/backup/recursive-type/src/data-structures/heap/index.ts +3 -0
  49. package/backup/recursive-type/src/data-structures/heap/max-heap.ts +31 -0
  50. package/backup/recursive-type/src/data-structures/heap/min-heap.ts +34 -0
  51. package/backup/recursive-type/src/data-structures/index.ts +15 -0
  52. package/backup/recursive-type/src/data-structures/interfaces/abstract-graph.ts +42 -0
  53. package/backup/recursive-type/src/data-structures/interfaces/avl-tree.ts +1 -0
  54. package/backup/recursive-type/src/data-structures/interfaces/binary-tree.ts +56 -0
  55. package/backup/recursive-type/src/data-structures/interfaces/bst.ts +1 -0
  56. package/backup/recursive-type/src/data-structures/interfaces/directed-graph.ts +15 -0
  57. package/backup/recursive-type/src/data-structures/interfaces/doubly-linked-list.ts +1 -0
  58. package/backup/recursive-type/src/data-structures/interfaces/heap.ts +1 -0
  59. package/backup/recursive-type/src/data-structures/interfaces/index.ts +13 -0
  60. package/backup/recursive-type/src/data-structures/interfaces/navigator.ts +1 -0
  61. package/backup/recursive-type/src/data-structures/interfaces/priority-queue.ts +1 -0
  62. package/backup/recursive-type/src/data-structures/interfaces/segment-tree.ts +1 -0
  63. package/backup/recursive-type/src/data-structures/interfaces/singly-linked-list.ts +1 -0
  64. package/backup/recursive-type/src/data-structures/interfaces/tree-multiset.ts +1 -0
  65. package/backup/recursive-type/src/data-structures/interfaces/undirected-graph.ts +3 -0
  66. package/backup/recursive-type/src/data-structures/linked-list/doubly-linked-list.ts +573 -0
  67. package/backup/recursive-type/src/data-structures/linked-list/index.ts +3 -0
  68. package/backup/recursive-type/src/data-structures/linked-list/singly-linked-list.ts +490 -0
  69. package/backup/recursive-type/src/data-structures/linked-list/skip-linked-list.ts +3 -0
  70. package/backup/recursive-type/src/data-structures/matrix/index.ts +4 -0
  71. package/backup/recursive-type/src/data-structures/matrix/matrix.ts +27 -0
  72. package/backup/recursive-type/src/data-structures/matrix/matrix2d.ts +208 -0
  73. package/backup/recursive-type/src/data-structures/matrix/navigator.ts +122 -0
  74. package/backup/recursive-type/src/data-structures/matrix/vector2d.ts +316 -0
  75. package/backup/recursive-type/src/data-structures/priority-queue/index.ts +3 -0
  76. package/backup/recursive-type/src/data-structures/priority-queue/max-priority-queue.ts +49 -0
  77. package/backup/recursive-type/src/data-structures/priority-queue/min-priority-queue.ts +50 -0
  78. package/backup/recursive-type/src/data-structures/priority-queue/priority-queue.ts +354 -0
  79. package/backup/recursive-type/src/data-structures/queue/deque.ts +251 -0
  80. package/backup/recursive-type/src/data-structures/queue/index.ts +2 -0
  81. package/backup/recursive-type/src/data-structures/queue/queue.ts +120 -0
  82. package/backup/recursive-type/src/data-structures/stack/index.ts +1 -0
  83. package/backup/recursive-type/src/data-structures/stack/stack.ts +98 -0
  84. package/backup/recursive-type/src/data-structures/tree/index.ts +1 -0
  85. package/backup/recursive-type/src/data-structures/tree/tree.ts +80 -0
  86. package/backup/recursive-type/src/data-structures/trie/index.ts +1 -0
  87. package/backup/recursive-type/src/data-structures/trie/trie.ts +227 -0
  88. package/backup/recursive-type/src/data-structures/types/abstract-graph.ts +5 -0
  89. package/backup/recursive-type/src/data-structures/types/avl-tree.ts +8 -0
  90. package/backup/recursive-type/src/data-structures/types/binary-tree.ts +10 -0
  91. package/backup/recursive-type/src/data-structures/types/bst.ts +6 -0
  92. package/backup/recursive-type/src/data-structures/types/directed-graph.ts +8 -0
  93. package/backup/recursive-type/src/data-structures/types/doubly-linked-list.ts +1 -0
  94. package/backup/recursive-type/src/data-structures/types/heap.ts +5 -0
  95. package/backup/recursive-type/src/data-structures/types/index.ts +12 -0
  96. package/backup/recursive-type/src/data-structures/types/navigator.ts +13 -0
  97. package/backup/recursive-type/src/data-structures/types/priority-queue.ts +9 -0
  98. package/backup/recursive-type/src/data-structures/types/segment-tree.ts +1 -0
  99. package/backup/recursive-type/src/data-structures/types/singly-linked-list.ts +1 -0
  100. package/backup/recursive-type/src/data-structures/types/tree-multiset.ts +1 -0
  101. package/backup/recursive-type/src/index.ts +1 -0
  102. package/backup/recursive-type/src/utils/index.ts +2 -0
  103. package/backup/recursive-type/src/utils/types/index.ts +1 -0
  104. package/backup/recursive-type/src/utils/types/utils.ts +6 -0
  105. package/backup/recursive-type/src/utils/utils.ts +78 -0
  106. package/dist/data-structures/binary-tree/abstract-binary-tree.d.ts +333 -0
  107. package/dist/data-structures/binary-tree/abstract-binary-tree.js +1455 -0
  108. package/dist/data-structures/binary-tree/avl-tree.d.ts +20 -25
  109. package/dist/data-structures/binary-tree/avl-tree.js +10 -18
  110. package/dist/data-structures/binary-tree/binary-tree.d.ts +18 -345
  111. package/dist/data-structures/binary-tree/binary-tree.js +39 -1444
  112. package/dist/data-structures/binary-tree/bst.d.ts +24 -31
  113. package/dist/data-structures/binary-tree/bst.js +46 -53
  114. package/dist/data-structures/binary-tree/index.d.ts +1 -0
  115. package/dist/data-structures/binary-tree/index.js +1 -0
  116. package/dist/data-structures/binary-tree/rb-tree.d.ts +1 -2
  117. package/dist/data-structures/binary-tree/rb-tree.js +64 -5
  118. package/dist/data-structures/binary-tree/tree-multiset.d.ts +11 -25
  119. package/dist/data-structures/binary-tree/tree-multiset.js +29 -31
  120. package/dist/data-structures/graph/abstract-graph.d.ts +56 -58
  121. package/dist/data-structures/graph/abstract-graph.js +84 -68
  122. package/dist/data-structures/graph/directed-graph.d.ts +124 -95
  123. package/dist/data-structures/graph/directed-graph.js +156 -108
  124. package/dist/data-structures/graph/undirected-graph.d.ts +83 -58
  125. package/dist/data-structures/graph/undirected-graph.js +98 -71
  126. package/dist/data-structures/hash/coordinate-set.d.ts +1 -1
  127. package/dist/data-structures/index.d.ts +1 -0
  128. package/dist/data-structures/index.js +1 -0
  129. package/dist/data-structures/interfaces/abstract-graph.d.ts +22 -0
  130. package/dist/data-structures/interfaces/abstract-graph.js +2 -0
  131. package/dist/data-structures/interfaces/avl-tree.d.ts +1 -0
  132. package/dist/data-structures/interfaces/avl-tree.js +2 -0
  133. package/dist/data-structures/interfaces/binary-tree.d.ts +26 -0
  134. package/dist/data-structures/interfaces/binary-tree.js +2 -0
  135. package/dist/data-structures/interfaces/bst.d.ts +1 -0
  136. package/dist/data-structures/interfaces/bst.js +2 -0
  137. package/dist/data-structures/interfaces/directed-graph.d.ts +9 -0
  138. package/dist/data-structures/interfaces/directed-graph.js +2 -0
  139. package/dist/data-structures/interfaces/doubly-linked-list.d.ts +1 -0
  140. package/dist/data-structures/interfaces/doubly-linked-list.js +2 -0
  141. package/dist/data-structures/interfaces/heap.d.ts +1 -0
  142. package/dist/data-structures/interfaces/heap.js +2 -0
  143. package/dist/data-structures/interfaces/index.d.ts +13 -0
  144. package/dist/data-structures/interfaces/index.js +29 -0
  145. package/dist/data-structures/interfaces/navigator.d.ts +1 -0
  146. package/dist/data-structures/interfaces/navigator.js +2 -0
  147. package/dist/data-structures/interfaces/priority-queue.d.ts +1 -0
  148. package/dist/data-structures/interfaces/priority-queue.js +2 -0
  149. package/dist/data-structures/interfaces/segment-tree.d.ts +1 -0
  150. package/dist/data-structures/interfaces/segment-tree.js +2 -0
  151. package/dist/data-structures/interfaces/singly-linked-list.d.ts +1 -0
  152. package/dist/data-structures/interfaces/singly-linked-list.js +2 -0
  153. package/dist/data-structures/interfaces/tree-multiset.d.ts +1 -0
  154. package/dist/data-structures/interfaces/tree-multiset.js +2 -0
  155. package/dist/data-structures/interfaces/undirected-graph.d.ts +2 -0
  156. package/dist/data-structures/interfaces/undirected-graph.js +2 -0
  157. package/dist/data-structures/linked-list/doubly-linked-list.d.ts +1 -1
  158. package/dist/data-structures/linked-list/singly-linked-list.d.ts +1 -1
  159. package/dist/data-structures/priority-queue/priority-queue.d.ts +1 -1
  160. package/dist/data-structures/priority-queue/priority-queue.js +4 -4
  161. package/dist/data-structures/queue/deque.d.ts +5 -5
  162. package/dist/data-structures/queue/deque.js +6 -6
  163. package/dist/data-structures/queue/queue.d.ts +1 -1
  164. package/dist/data-structures/stack/stack.d.ts +1 -1
  165. package/dist/data-structures/types/abstract-binary-tree.d.ts +32 -0
  166. package/dist/data-structures/types/abstract-binary-tree.js +21 -0
  167. package/dist/data-structures/types/abstract-graph.d.ts +1 -20
  168. package/dist/data-structures/types/avl-tree.d.ts +3 -4
  169. package/dist/data-structures/types/binary-tree.d.ts +3 -10
  170. package/dist/data-structures/types/bst.d.ts +10 -4
  171. package/dist/data-structures/types/bst.js +7 -0
  172. package/dist/data-structures/types/directed-graph.d.ts +5 -9
  173. package/dist/data-structures/types/directed-graph.js +7 -0
  174. package/dist/data-structures/types/heap.d.ts +2 -2
  175. package/dist/data-structures/types/helpers.d.ts +8 -0
  176. package/dist/data-structures/types/helpers.js +2 -0
  177. package/dist/data-structures/types/index.d.ts +3 -1
  178. package/dist/data-structures/types/index.js +3 -1
  179. package/dist/data-structures/types/navigator.d.ts +2 -2
  180. package/dist/data-structures/types/priority-queue.d.ts +2 -2
  181. package/dist/data-structures/types/rb-tree.d.ts +6 -0
  182. package/dist/data-structures/types/rb-tree.js +8 -0
  183. package/dist/data-structures/types/tree-multiset.d.ts +5 -4
  184. package/docs/assets/search.js +1 -1
  185. package/docs/classes/AVLTree.html +310 -309
  186. package/docs/classes/AVLTreeNode.html +122 -68
  187. package/docs/classes/AaTree.html +30 -17
  188. package/docs/classes/AbstractBinaryTree.html +2023 -0
  189. package/docs/classes/AbstractBinaryTreeNode.html +491 -0
  190. package/docs/classes/AbstractEdge.html +84 -39
  191. package/docs/classes/AbstractGraph.html +235 -119
  192. package/docs/classes/AbstractVertex.html +87 -35
  193. package/docs/classes/ArrayDeque.html +43 -30
  194. package/docs/classes/BST.html +297 -285
  195. package/docs/classes/BSTNode.html +123 -62
  196. package/docs/classes/BTree.html +30 -17
  197. package/docs/classes/BinaryIndexedTree.html +38 -25
  198. package/docs/classes/BinaryTree.html +596 -589
  199. package/docs/classes/BinaryTreeNode.html +181 -161
  200. package/docs/classes/Character.html +33 -20
  201. package/docs/classes/CoordinateMap.html +38 -25
  202. package/docs/classes/CoordinateSet.html +39 -26
  203. package/docs/classes/Deque.html +63 -50
  204. package/docs/classes/DirectedEdge.html +90 -46
  205. package/docs/classes/DirectedGraph.html +374 -212
  206. package/docs/classes/DirectedVertex.html +79 -41
  207. package/docs/classes/DoublyLinkedList.html +68 -55
  208. package/docs/classes/DoublyLinkedListNode.html +40 -27
  209. package/docs/classes/HashTable.html +30 -17
  210. package/docs/classes/Heap.html +45 -32
  211. package/docs/classes/HeapItem.html +37 -24
  212. package/docs/classes/Matrix2D.html +45 -32
  213. package/docs/classes/MatrixNTI2D.html +33 -20
  214. package/docs/classes/MaxHeap.html +45 -32
  215. package/docs/classes/MaxPriorityQueue.html +83 -65
  216. package/docs/classes/MinHeap.html +45 -32
  217. package/docs/classes/MinPriorityQueue.html +83 -65
  218. package/docs/classes/Navigator.html +40 -27
  219. package/docs/classes/ObjectDeque.html +78 -55
  220. package/docs/classes/Pair.html +30 -17
  221. package/docs/classes/PriorityQueue.html +78 -60
  222. package/docs/classes/Queue.html +45 -32
  223. package/docs/classes/SegmentTree.html +46 -33
  224. package/docs/classes/SegmentTreeNode.html +49 -36
  225. package/docs/classes/SinglyLinkedList.html +65 -52
  226. package/docs/classes/SinglyLinkedListNode.html +37 -24
  227. package/docs/classes/SkipLinkedList.html +30 -17
  228. package/docs/classes/SplayTree.html +30 -17
  229. package/docs/classes/Stack.html +43 -30
  230. package/docs/classes/TreeMap.html +30 -17
  231. package/docs/classes/TreeMultiSet.html +330 -316
  232. package/docs/classes/TreeMultiSetNode.html +450 -0
  233. package/docs/classes/TreeNode.html +45 -32
  234. package/docs/classes/TreeSet.html +30 -17
  235. package/docs/classes/Trie.html +42 -29
  236. package/docs/classes/TrieNode.html +40 -27
  237. package/docs/classes/TwoThreeTree.html +30 -17
  238. package/docs/classes/UndirectedEdge.html +86 -56
  239. package/docs/classes/UndirectedGraph.html +286 -165
  240. package/docs/classes/UndirectedVertex.html +79 -41
  241. package/docs/classes/Vector2D.html +57 -44
  242. package/docs/enums/CP.html +36 -23
  243. package/docs/enums/FamilyPosition.html +48 -35
  244. package/docs/enums/LoopType.html +42 -29
  245. package/docs/{interfaces/PriorityQueueOptions.html → enums/RBColor.html} +52 -55
  246. package/docs/{interfaces/AVLTreeDeleted.html → enums/TopologicalProperty.html} +59 -48
  247. package/docs/index.html +211 -73
  248. package/docs/interfaces/{NavigatorParams.html → IBinaryTree.html} +56 -67
  249. package/docs/interfaces/IBinaryTreeNode.html +396 -0
  250. package/docs/interfaces/IDirectedGraph.html +36 -23
  251. package/docs/interfaces/IGraph.html +134 -93
  252. package/docs/interfaces/{HeapOptions.html → IUNDirectedGraph.html} +38 -57
  253. package/docs/modules.html +57 -31
  254. package/docs/types/{ToThunkFn.html → AVLTreeOptions.html} +35 -27
  255. package/docs/types/AbstractBinaryTreeOptions.html +150 -0
  256. package/docs/types/AbstractRecursiveBinaryTreeNode.html +146 -0
  257. package/docs/types/{ResultsByProperty.html → AbstractResultByProperty.html} +35 -22
  258. package/docs/types/{TreeMultiSetDeletedResult.html → AbstractResultsByProperty.html} +35 -29
  259. package/docs/types/BSTComparator.html +30 -17
  260. package/docs/types/{TrlAsyncFn.html → BSTOptions.html} +36 -31
  261. package/docs/types/BinaryTreeDeletedResult.html +153 -0
  262. package/docs/types/BinaryTreeNodeId.html +30 -17
  263. package/docs/types/BinaryTreeNodePropertyName.html +30 -17
  264. package/docs/types/{BinaryTreeDeleted.html → BinaryTreeOptions.html} +35 -31
  265. package/docs/types/DFSOrderPattern.html +30 -17
  266. package/docs/types/DijkstraResult.html +30 -17
  267. package/docs/types/Direction.html +30 -17
  268. package/docs/types/{SpecifyOptional.html → EdgeId.html} +34 -28
  269. package/docs/types/{TrlFn.html → HeapOptions.html} +45 -24
  270. package/docs/types/IdObject.html +151 -0
  271. package/docs/types/{BSTDeletedResult.html → KeyValObject.html} +36 -30
  272. package/docs/types/NavigatorParams.html +175 -0
  273. package/docs/types/NodeOrPropertyName.html +30 -17
  274. package/docs/types/PriorityQueueComparator.html +30 -17
  275. package/docs/types/PriorityQueueDFSOrderPattern.html +30 -17
  276. package/docs/types/PriorityQueueOptions.html +155 -0
  277. package/docs/types/{Thunk.html → RBTreeOptions.html} +35 -27
  278. package/docs/types/RecursiveAVLTreeNode.html +146 -0
  279. package/docs/types/RecursiveBSTNode.html +146 -0
  280. package/docs/types/RecursiveBinaryTreeNode.html +146 -0
  281. package/docs/types/RecursiveTreeMultiSetNode.html +146 -0
  282. package/docs/types/SegmentTreeNodeVal.html +30 -17
  283. package/docs/types/TopologicalStatus.html +30 -17
  284. package/docs/types/TreeMultiSetOptions.html +146 -0
  285. package/docs/types/Turning.html +30 -17
  286. package/docs/types/VertexId.html +30 -17
  287. package/notes/note.md +8 -1
  288. package/package.json +10 -2
  289. package/docs/classes/RBTree.html +0 -153
  290. package/docs/types/ResultByProperty.html +0 -133
@@ -0,0 +1,985 @@
1
+ /**
2
+ * data-structure-typed
3
+ *
4
+ * @author Tyler Zeng
5
+ * @copyright Copyright (c) 2022 Tyler Zeng <zrwusa@gmail.com>
6
+ * @license MIT License
7
+ */
8
+ import {arrayRemove, uuidV4} from '../../utils';
9
+ import {PriorityQueue} from '../priority-queue';
10
+ import type {DijkstraResult, VertexId} from '../types';
11
+ import {IGraph} from '../interfaces';
12
+
13
+ export abstract class AbstractVertex<T = number> {
14
+
15
+ protected constructor(id: VertexId, val?: T) {
16
+ this._id = id;
17
+ this._val = val;
18
+ }
19
+
20
+ private _id: VertexId;
21
+
22
+ get id(): VertexId {
23
+ return this._id;
24
+ }
25
+
26
+ set id(v: VertexId) {
27
+ this._id = v;
28
+ }
29
+
30
+ private _val: T | undefined;
31
+
32
+ get val(): T | undefined {
33
+ return this._val;
34
+ }
35
+
36
+ set val(value: T | undefined) {
37
+ this._val = value;
38
+ }
39
+
40
+ // /**
41
+ // * In TypeScript, a subclass inherits the interface implementation of its parent class, without needing to implement the same interface again in the subclass. This behavior differs from Java's approach. In Java, if a parent class implements an interface, the subclass needs to explicitly implement the same interface, even if the parent class has already implemented it.
42
+ // * This means that using abstract methods in the parent class cannot constrain the grandchild classes. Defining methods within an interface also cannot constrain the descendant classes. When inheriting from this class, developers need to be aware that this method needs to be overridden.
43
+ // * @param id
44
+ // * @param val
45
+ // */
46
+ // abstract _createVertex(id: VertexId, val?: T): AbstractVertex<T>;
47
+ }
48
+
49
+ export abstract class AbstractEdge<T> {
50
+
51
+ protected constructor(weight?: number, val?: T) {
52
+ this._weight = weight !== undefined ? weight : 1;
53
+ this._val = val;
54
+ this._hashCode = uuidV4();
55
+ }
56
+
57
+ private _val: T | undefined;
58
+
59
+ get val(): T | undefined {
60
+ return this._val;
61
+ }
62
+
63
+ set val(value: T | undefined) {
64
+ this._val = value;
65
+ }
66
+
67
+ private _weight: number;
68
+
69
+ get weight(): number {
70
+ return this._weight;
71
+ }
72
+
73
+ set weight(v: number) {
74
+ this._weight = v;
75
+ }
76
+
77
+ protected _hashCode: string;
78
+
79
+ get hashCode(): string {
80
+ return this._hashCode;
81
+ }
82
+
83
+ // /**
84
+ // * In TypeScript, a subclass inherits the interface implementation of its parent class, without needing to implement the same interface again in the subclass. This behavior differs from Java's approach. In Java, if a parent class implements an interface, the subclass needs to explicitly implement the same interface, even if the parent class has already implemented it.
85
+ // * This means that using abstract methods in the parent class cannot constrain the grandchild classes. Defining methods within an interface also cannot constrain the descendant classes. When inheriting from this class, developers need to be aware that this method needs to be overridden.
86
+ // * @param srcOrV1
87
+ // * @param destOrV2
88
+ // * @param weight
89
+ // * @param val
90
+ // */
91
+ // abstract _createEdge(srcOrV1: VertexId | string, destOrV2: VertexId | string, weight?: number, val?: E): E;
92
+
93
+ protected _setHashCode(v: string) {
94
+ this._hashCode = v;
95
+ }
96
+ }
97
+
98
+ // Connected Component === Largest Connected Sub-Graph
99
+ export abstract class AbstractGraph<V extends AbstractVertex<any>, E extends AbstractEdge<any>> implements IGraph<V, E> {
100
+ private _vertices: Map<VertexId, V> = new Map<VertexId, V>();
101
+
102
+ get vertices(): Map<VertexId, V> {
103
+ return this._vertices;
104
+ }
105
+
106
+ /**
107
+ * In TypeScript, a subclass inherits the interface implementation of its parent class, without needing to implement the same interface again in the subclass. This behavior differs from Java's approach. In Java, if a parent class implements an interface, the subclass needs to explicitly implement the same interface, even if the parent class has already implemented it.
108
+ * This means that using abstract methods in the parent class cannot constrain the grandchild classes. Defining methods within an interface also cannot constrain the descendant classes. When inheriting from this class, developers need to be aware that this method needs to be overridden.
109
+ * @param id
110
+ * @param val
111
+ */
112
+ abstract _createVertex(id: VertexId, val?: V): V;
113
+
114
+ /**
115
+ * In TypeScript, a subclass inherits the interface implementation of its parent class, without needing to implement the same interface again in the subclass. This behavior differs from Java's approach. In Java, if a parent class implements an interface, the subclass needs to explicitly implement the same interface, even if the parent class has already implemented it.
116
+ * This means that using abstract methods in the parent class cannot constrain the grandchild classes. Defining methods within an interface also cannot constrain the descendant classes. When inheriting from this class, developers need to be aware that this method needs to be overridden.
117
+ * @param srcOrV1
118
+ * @param destOrV2
119
+ * @param weight
120
+ * @param val
121
+ */
122
+ abstract _createEdge(srcOrV1: VertexId | string, destOrV2: VertexId | string, weight?: number, val?: E): E;
123
+
124
+ abstract removeEdgeBetween(srcOrId: V | VertexId, destOrId: V | VertexId): E | null;
125
+
126
+ abstract removeEdge(edge: E): E | null;
127
+
128
+ _getVertex(vertexOrId: VertexId | V): V | null {
129
+ const vertexId = this._getVertexId(vertexOrId);
130
+ return this._vertices.get(vertexId) || null;
131
+ }
132
+
133
+ getVertex(vertexId: VertexId): V | null {
134
+ return this._vertices.get(vertexId) || null;
135
+ }
136
+
137
+ _getVertexId(vertexOrId: V | VertexId): VertexId {
138
+ return vertexOrId instanceof AbstractVertex ? vertexOrId.id : vertexOrId;
139
+ }
140
+
141
+ /**
142
+ * The function checks if a vertex exists in a graph.
143
+ * @param {V | VertexId} vertexOrId - The parameter `vertexOrId` can accept either a vertex object (`V`) or a vertex ID
144
+ * (`VertexId`).
145
+ * @returns The method `hasVertex` returns a boolean value.
146
+ */
147
+ hasVertex(vertexOrId: V | VertexId): boolean {
148
+ return this._vertices.has(this._getVertexId(vertexOrId));
149
+ }
150
+
151
+ abstract getEdge(srcOrId: V | VertexId, destOrId: V | VertexId): E | null;
152
+
153
+ createAddVertex(id: VertexId, val?: V['val']): boolean {
154
+ const newVertex = this._createVertex(id, val);
155
+ return this.addVertex(newVertex);
156
+ }
157
+
158
+ addVertex(newVertex: V): boolean {
159
+ if (this.hasVertex(newVertex)) {
160
+ throw (new Error('Duplicated vertex id is not allowed'));
161
+ }
162
+ this._vertices.set(newVertex.id, newVertex);
163
+ return true;
164
+ }
165
+
166
+ /**
167
+ * The `removeVertex` function removes a vertex from a graph by its ID or by the vertex object itself.
168
+ * @param {V | VertexId} vertexOrId - The parameter `vertexOrId` can be either a vertex object (`V`) or a vertex ID
169
+ * (`VertexId`).
170
+ * @returns The method `removeVertex` returns a boolean value.
171
+ */
172
+ removeVertex(vertexOrId: V | VertexId): boolean {
173
+ const vertexId = this._getVertexId(vertexOrId);
174
+ return this._vertices.delete(vertexId);
175
+ }
176
+
177
+ /**
178
+ * The function removes all vertices from a graph and returns a boolean indicating if any vertices were removed.
179
+ * @param {V[] | VertexId[]} vertices - The `vertices` parameter can be either an array of vertices (`V[]`) or an array
180
+ * of vertex IDs (`VertexId[]`).
181
+ * @returns a boolean value. It returns true if at least one vertex was successfully removed, and false if no vertices
182
+ * were removed.
183
+ */
184
+ removeAllVertices(vertices: V[] | VertexId[]): boolean {
185
+ const removed: boolean[] = [];
186
+ for (const v of vertices) {
187
+ removed.push(this.removeVertex(v));
188
+ }
189
+ return removed.length > 0;
190
+ }
191
+
192
+ abstract degreeOf(vertexOrId: V | VertexId): number;
193
+
194
+ abstract edgeSet(): E[];
195
+
196
+ abstract edgesOf(vertexOrId: V | VertexId): E[];
197
+
198
+ /**
199
+ * The function checks if there is an edge between two vertices in a graph.
200
+ * @param {VertexId | V} v1 - The parameter v1 can be either a VertexId or a V. A VertexId represents the identifier of
201
+ * a vertex in a graph, while V represents the type of the vertex itself.
202
+ * @param {VertexId | V} v2 - The parameter `v2` represents the second vertex in an edge. It can be either a `VertexId`
203
+ * or a `V` type.
204
+ * @returns The function `hasEdge` returns a boolean value. It returns `true` if there is an edge between the
205
+ * vertices `v1` and `v2`, and `false` otherwise.
206
+ */
207
+ hasEdge(v1: VertexId | V, v2: VertexId | V): boolean {
208
+ const edge = this.getEdge(v1, v2);
209
+ return !!edge;
210
+ }
211
+
212
+ createAddEdge(src: V | VertexId, dest: V | VertexId, weight: number, val: E['val']): boolean {
213
+ if (src instanceof AbstractVertex) src = src.id;
214
+ if (dest instanceof AbstractVertex) dest = dest.id;
215
+ const newEdge = this._createEdge(src, dest, weight, val);
216
+ return this.addEdge(newEdge);
217
+ }
218
+
219
+ abstract addEdge(edge: E): boolean;
220
+
221
+ /**
222
+ * The function sets the weight of an edge between two vertices in a graph.
223
+ * @param {VertexId | V} srcOrId - The `srcOrId` parameter can be either a `VertexId` or a `V` object. It represents
224
+ * the source vertex of the edge.
225
+ * @param {VertexId | V} destOrId - The `destOrId` parameter represents the destination vertex of the edge. It can be
226
+ * either a `VertexId` or a vertex object `V`.
227
+ * @param {number} weight - The weight parameter represents the weight of the edge between the source vertex (srcOrId)
228
+ * and the destination vertex (destOrId).
229
+ * @returns a boolean value. If the edge exists between the source and destination vertices, the function will update
230
+ * the weight of the edge and return true. If the edge does not exist, the function will return false.
231
+ */
232
+ setEdgeWeight(srcOrId: VertexId | V, destOrId: VertexId | V, weight: number): boolean {
233
+ const edge = this.getEdge(srcOrId, destOrId);
234
+ if (edge) {
235
+ edge.weight = weight;
236
+ return true;
237
+ } else {
238
+ return false;
239
+ }
240
+ }
241
+
242
+ abstract getNeighbors(vertexOrId: V | VertexId): V[];
243
+
244
+ /**
245
+ * The function `getAllPathsBetween` finds all paths between two vertices in a graph using depth-first search.
246
+ * @param {V | VertexId} v1 - The parameter `v1` represents either a vertex object (`V`) or a vertex ID (`VertexId`).
247
+ * It is the starting vertex for finding paths.
248
+ * @param {V | VertexId} v2 - The parameter `v2` represents the destination vertex or its ID. It is the vertex that we
249
+ * want to find paths to from the starting vertex `v1`.
250
+ * @returns an array of arrays of vertices (V[][]). Each inner array represents a path between the given vertices (v1
251
+ * and v2).
252
+ */
253
+ getAllPathsBetween(v1: V | VertexId, v2: V | VertexId): V[][] {
254
+ const paths: V[][] = [];
255
+ const vertex1 = this._getVertex(v1);
256
+ const vertex2 = this._getVertex(v2);
257
+ if (!(vertex1 && vertex2)) {
258
+ return [];
259
+ }
260
+
261
+ const dfs = (cur: V, dest: V, visiting: Map<V, boolean>, path: V[]) => {
262
+ visiting.set(cur, true);
263
+
264
+ if (cur === dest) {
265
+ paths.push([vertex1, ...path]);
266
+ }
267
+
268
+ const neighbors = this.getNeighbors(cur);
269
+ for (const neighbor of neighbors) {
270
+ if (!visiting.get(neighbor)) {
271
+ path.push(neighbor);
272
+ dfs(neighbor, dest, visiting, path);
273
+ arrayRemove(path, (vertex: V) => vertex === neighbor);
274
+ }
275
+ }
276
+
277
+ visiting.set(cur, false);
278
+ };
279
+
280
+ dfs(vertex1, vertex2, new Map<V, boolean>(), []);
281
+ return paths;
282
+ }
283
+
284
+ /**
285
+ * The function calculates the sum of weights along a given path.
286
+ * @param {V[]} path - An array of vertices (V) representing a path in a graph.
287
+ * @returns The function `getPathSumWeight` returns the sum of the weights of the edges in the given path.
288
+ */
289
+ getPathSumWeight(path: V[]): number {
290
+ let sum = 0;
291
+ for (let i = 0; i < path.length; i++) {
292
+ sum += this.getEdge(path[i], path[i + 1])?.weight || 0;
293
+ }
294
+ return sum;
295
+ }
296
+
297
+ /**
298
+ * The function `getMinCostBetween` calculates the minimum cost between two vertices in a graph, either based on edge
299
+ * weights or using a breadth-first search algorithm.
300
+ * @param {V | VertexId} v1 - The parameter `v1` represents the starting vertex or vertex ID of the graph.
301
+ * @param {V | VertexId} v2 - The parameter `v2` represents the second vertex in the graph. It can be either a vertex
302
+ * object or a vertex ID.
303
+ * @param {boolean} [isWeight] - isWeight is an optional parameter that indicates whether the graph edges have weights.
304
+ * If isWeight is set to true, the function will calculate the minimum cost between v1 and v2 based on the weights of
305
+ * the edges. If isWeight is set to false or not provided, the function will calculate the
306
+ * @returns The function `getMinCostBetween` returns a number representing the minimum cost between two vertices (`v1`
307
+ * and `v2`) in a graph. If the `isWeight` parameter is `true`, it calculates the minimum weight between the vertices.
308
+ * If `isWeight` is `false` or not provided, it calculates the minimum number of edges between the vertices. If the
309
+ * vertices are not
310
+ */
311
+ getMinCostBetween(v1: V | VertexId, v2: V | VertexId, isWeight?: boolean): number | null {
312
+ if (isWeight === undefined) isWeight = false;
313
+
314
+ if (isWeight) {
315
+ const allPaths = this.getAllPathsBetween(v1, v2);
316
+ let min = Infinity;
317
+ for (const path of allPaths) {
318
+ min = Math.min(this.getPathSumWeight(path), min);
319
+ }
320
+ return min;
321
+ } else {
322
+ // BFS
323
+ const vertex2 = this._getVertex(v2);
324
+ const vertex1 = this._getVertex(v1);
325
+ if (!(vertex1 && vertex2)) {
326
+ return null;
327
+ }
328
+
329
+ const visited: Map<V, boolean> = new Map();
330
+ const queue: V[] = [vertex1];
331
+ visited.set(vertex1, true);
332
+ let cost = 0;
333
+ while (queue.length > 0) {
334
+ for (let i = 0; i < queue.length; i++) {
335
+ const cur = queue.shift();
336
+ if (cur === vertex2) {
337
+ return cost;
338
+ }
339
+ // TODO consider optimizing to AbstractGraph
340
+ if (cur !== undefined) {
341
+ const neighbors = this.getNeighbors(cur);
342
+ for (const neighbor of neighbors) {
343
+ if (!visited.has(neighbor)) {
344
+ visited.set(neighbor, true);
345
+ queue.push(neighbor);
346
+ }
347
+ }
348
+ }
349
+ }
350
+ cost++;
351
+ }
352
+ return null;
353
+ }
354
+ }
355
+
356
+ /**
357
+ * The function `getMinPathBetween` returns the minimum path between two vertices in a graph, either based on weight or
358
+ * using a breadth-first search algorithm.
359
+ * @param {V | VertexId} v1 - The parameter `v1` represents the starting vertex or its ID.
360
+ * @param {V | VertexId} v2 - The parameter `v2` represents the destination vertex or its ID. It is the vertex that we
361
+ * want to find the minimum path to from the source vertex `v1`.
362
+ * @param {boolean} [isWeight] - A boolean flag indicating whether to consider the weight of edges in finding the
363
+ * minimum path. If set to true, the function will use Dijkstra's algorithm to find the minimum weighted path. If set
364
+ * to false, the function will use breadth-first search (BFS) to find the minimum path. If
365
+ * @returns The function `getMinPathBetween` returns an array of vertices (`V[]`) representing the minimum path between
366
+ * two vertices (`v1` and `v2`). If no path is found, it returns `null`.
367
+ */
368
+ getMinPathBetween(v1: V | VertexId, v2: V | VertexId, isWeight?: boolean): V[] | null {
369
+ if (isWeight === undefined) isWeight = false;
370
+
371
+ if (isWeight) {
372
+ const allPaths = this.getAllPathsBetween(v1, v2);
373
+ let min = Infinity;
374
+ let minIndex = -1;
375
+ let index = 0;
376
+ for (const path of allPaths) {
377
+ const pathSumWeight = this.getPathSumWeight(path);
378
+ if (pathSumWeight < min) {
379
+ min = pathSumWeight;
380
+ minIndex = index;
381
+ }
382
+ index++;
383
+ }
384
+ return allPaths[minIndex] || null;
385
+ } else {
386
+ // BFS
387
+ let minPath: V[] = [];
388
+ const vertex1 = this._getVertex(v1);
389
+ const vertex2 = this._getVertex(v2);
390
+ if (!(vertex1 && vertex2)) {
391
+ return [];
392
+ }
393
+
394
+ const dfs = (cur: V, dest: V, visiting: Map<V, boolean>, path: V[]) => {
395
+ visiting.set(cur, true);
396
+
397
+ if (cur === dest) {
398
+ minPath = [vertex1, ...path];
399
+ return;
400
+ }
401
+
402
+ const neighbors = this.getNeighbors(cur);
403
+ for (const neighbor of neighbors) {
404
+ if (!visiting.get(neighbor)) {
405
+ path.push(neighbor);
406
+ dfs(neighbor, dest, visiting, path);
407
+ arrayRemove(path, (vertex: V) => vertex === neighbor);
408
+ }
409
+ }
410
+
411
+ visiting.set(cur, false);
412
+ };
413
+
414
+ dfs(vertex1, vertex2, new Map<V, boolean>(), []);
415
+ return minPath;
416
+ }
417
+ }
418
+
419
+ /**
420
+ * Dijkstra algorithm time: O(VE) space: O(V + E)
421
+ * The function `dijkstraWithoutHeap` implements Dijkstra's algorithm to find the shortest path between two vertices in
422
+ * a graph without using a heap data structure.
423
+ * @param {V | VertexId} src - The source vertex from which to start the Dijkstra's algorithm. It can be either a
424
+ * vertex object or a vertex ID.
425
+ * @param {V | VertexId | null} [dest] - The `dest` parameter in the `dijkstraWithoutHeap` function is an optional
426
+ * parameter that specifies the destination vertex for the Dijkstra algorithm. It can be either a vertex object or its
427
+ * identifier. If no destination is provided, the value is set to `null`.
428
+ * @param {boolean} [getMinDist] - The `getMinDist` parameter is a boolean flag that determines whether the minimum
429
+ * distance from the source vertex to the destination vertex should be calculated and returned in the result. If
430
+ * `getMinDist` is set to `true`, the `minDist` property in the result will contain the minimum distance
431
+ * @param {boolean} [genPaths] - The `genPaths` parameter is a boolean flag that determines whether or not to generate
432
+ * paths in the Dijkstra algorithm. If `genPaths` is set to `true`, the algorithm will calculate and return the
433
+ * shortest paths from the source vertex to all other vertices in the graph. If `genPaths
434
+ * @returns The function `dijkstraWithoutHeap` returns an object of type `DijkstraResult<V>`.
435
+ */
436
+ dijkstraWithoutHeap(src: V | VertexId, dest?: V | VertexId | null, getMinDist?: boolean, genPaths?: boolean): DijkstraResult<V> {
437
+ if (getMinDist === undefined) getMinDist = false;
438
+ if (genPaths === undefined) genPaths = false;
439
+
440
+ if (dest === undefined) dest = null;
441
+ let minDist = Infinity;
442
+ let minDest: V | null = null;
443
+ let minPath: V[] = [];
444
+ const paths: V[][] = [];
445
+
446
+ const vertices = this._vertices;
447
+ const distMap: Map<V, number> = new Map();
448
+ const seen: Set<V> = new Set();
449
+ const preMap: Map<V, V | null> = new Map(); // predecessor
450
+ const srcVertex = this._getVertex(src);
451
+
452
+ const destVertex = dest ? this._getVertex(dest) : null;
453
+
454
+ if (!srcVertex) {
455
+ return null;
456
+ }
457
+
458
+ for (const vertex of vertices) {
459
+ const vertexOrId = vertex[1];
460
+ if (vertexOrId instanceof AbstractVertex) distMap.set(vertexOrId, Infinity);
461
+ }
462
+ distMap.set(srcVertex, 0);
463
+ preMap.set(srcVertex, null);
464
+
465
+ const getMinOfNoSeen = () => {
466
+ let min = Infinity;
467
+ let minV: V | null = null;
468
+ for (const [key, val] of distMap) {
469
+ if (!seen.has(key)) {
470
+ if (val < min) {
471
+ min = val;
472
+ minV = key;
473
+ }
474
+ }
475
+ }
476
+ return minV;
477
+ };
478
+
479
+ const getPaths = (minV: V | null) => {
480
+ for (const vertex of vertices) {
481
+ const vertexOrId = vertex[1];
482
+
483
+ if (vertexOrId instanceof AbstractVertex) {
484
+ const path: V[] = [vertexOrId];
485
+ let parent = preMap.get(vertexOrId);
486
+ while (parent) {
487
+ path.push(parent);
488
+ parent = preMap.get(parent);
489
+ }
490
+ const reversed = path.reverse();
491
+ if (vertex[1] === minV) minPath = reversed;
492
+ paths.push(reversed);
493
+ }
494
+ }
495
+ };
496
+
497
+ for (let i = 1; i < vertices.size; i++) {
498
+ const cur = getMinOfNoSeen();
499
+ if (cur) {
500
+ seen.add(cur);
501
+ if (destVertex && destVertex === cur) {
502
+ if (getMinDist) {
503
+ minDist = distMap.get(destVertex) || Infinity;
504
+ }
505
+ if (genPaths) {
506
+ getPaths(destVertex);
507
+ }
508
+ return {distMap, preMap, seen, paths, minDist, minPath};
509
+ }
510
+ const neighbors = this.getNeighbors(cur);
511
+ for (const neighbor of neighbors) {
512
+ if (!seen.has(neighbor)) {
513
+ const edge = this.getEdge(cur, neighbor);
514
+ if (edge) {
515
+ const curFromMap = distMap.get(cur);
516
+ const neighborFromMap = distMap.get(neighbor);
517
+ // TODO after no-non-null-assertion not ensure the logic
518
+ if (curFromMap !== undefined && neighborFromMap !== undefined) {
519
+ if (edge.weight + curFromMap < neighborFromMap) {
520
+ distMap.set(neighbor, edge.weight + curFromMap);
521
+ preMap.set(neighbor, cur);
522
+ }
523
+ }
524
+
525
+ }
526
+ }
527
+ }
528
+ }
529
+ }
530
+
531
+ getMinDist && distMap.forEach((d, v) => {
532
+ if (v !== srcVertex) {
533
+ if (d < minDist) {
534
+ minDist = d;
535
+ if (genPaths) minDest = v;
536
+ }
537
+ }
538
+ });
539
+
540
+ genPaths && getPaths(minDest);
541
+
542
+ return {distMap, preMap, seen, paths, minDist, minPath};
543
+ }
544
+
545
+ /**
546
+ * Dijkstra algorithm time: O(logVE) space: O(V + E)
547
+ * Dijkstra's algorithm is used to find the shortest paths from a source node to all other nodes in a graph. Its basic idea is to repeatedly choose the node closest to the source node and update the distances of other nodes using this node as an intermediary. Dijkstra's algorithm requires that the edge weights in the graph are non-negative.
548
+ * The `dijkstra` function implements Dijkstra's algorithm to find the shortest path between a source vertex and an
549
+ * optional destination vertex, and optionally returns the minimum distance, the paths, and other information.
550
+ * @param {V | VertexId} src - The `src` parameter represents the source vertex from which the Dijkstra algorithm will
551
+ * start. It can be either a vertex object or a vertex ID.
552
+ * @param {V | VertexId | null} [dest] - The `dest` parameter is the destination vertex or vertex ID. It specifies the
553
+ * vertex to which the shortest path is calculated from the source vertex. If no destination is provided, the algorithm
554
+ * will calculate the shortest paths to all other vertices from the source vertex.
555
+ * @param {boolean} [getMinDist] - The `getMinDist` parameter is a boolean flag that determines whether the minimum
556
+ * distance from the source vertex to the destination vertex should be calculated and returned in the result. If
557
+ * `getMinDist` is set to `true`, the `minDist` property in the result will contain the minimum distance
558
+ * @param {boolean} [genPaths] - The `genPaths` parameter is a boolean flag that determines whether or not to generate
559
+ * paths in the Dijkstra algorithm. If `genPaths` is set to `true`, the algorithm will calculate and return the
560
+ * shortest paths from the source vertex to all other vertices in the graph. If `genPaths
561
+ * @returns The function `dijkstra` returns an object of type `DijkstraResult<V>`.
562
+ */
563
+ dijkstra(src: V | VertexId, dest?: V | VertexId | null, getMinDist?: boolean, genPaths?: boolean): DijkstraResult<V> {
564
+ if (getMinDist === undefined) getMinDist = false;
565
+ if (genPaths === undefined) genPaths = false;
566
+
567
+ if (dest === undefined) dest = null;
568
+ let minDist = Infinity;
569
+ let minDest: V | null = null;
570
+ let minPath: V[] = [];
571
+ const paths: V[][] = [];
572
+ const vertices = this._vertices;
573
+ const distMap: Map<V, number> = new Map();
574
+ const seen: Set<V> = new Set();
575
+ const preMap: Map<V, V | null> = new Map(); // predecessor
576
+
577
+ const srcVertex = this._getVertex(src);
578
+ const destVertex = dest ? this._getVertex(dest) : null;
579
+
580
+ if (!srcVertex) {
581
+ return null;
582
+ }
583
+
584
+ for (const vertex of vertices) {
585
+ const vertexOrId = vertex[1];
586
+ if (vertexOrId instanceof AbstractVertex) distMap.set(vertexOrId, Infinity);
587
+ }
588
+
589
+ const heap = new PriorityQueue<{ id: number, val: V }>({comparator: (a, b) => a.id - b.id});
590
+ heap.add({id: 0, val: srcVertex});
591
+
592
+ distMap.set(srcVertex, 0);
593
+ preMap.set(srcVertex, null);
594
+
595
+ const getPaths = (minV: V | null) => {
596
+ for (const vertex of vertices) {
597
+ const vertexOrId = vertex[1];
598
+ if (vertexOrId instanceof AbstractVertex) {
599
+ const path: V[] = [vertexOrId];
600
+ let parent = preMap.get(vertexOrId);
601
+ while (parent) {
602
+ path.push(parent);
603
+ parent = preMap.get(parent);
604
+ }
605
+ const reversed = path.reverse();
606
+ if (vertex[1] === minV) minPath = reversed;
607
+ paths.push(reversed);
608
+ }
609
+
610
+ }
611
+ };
612
+
613
+ while (heap.size > 0) {
614
+ const curHeapNode = heap.poll();
615
+ const dist = curHeapNode?.id;
616
+ const cur = curHeapNode?.val;
617
+ if (dist !== undefined) {
618
+ if (cur) {
619
+ seen.add(cur);
620
+ if (destVertex && destVertex === cur) {
621
+ if (getMinDist) {
622
+ minDist = distMap.get(destVertex) || Infinity;
623
+ }
624
+ if (genPaths) {
625
+ getPaths(destVertex);
626
+ }
627
+ return {distMap, preMap, seen, paths, minDist, minPath};
628
+ }
629
+ const neighbors = this.getNeighbors(cur);
630
+ for (const neighbor of neighbors) {
631
+ if (!seen.has(neighbor)) {
632
+ const weight = this.getEdge(cur, neighbor)?.weight;
633
+ if (typeof weight === 'number') {
634
+ const distSrcToNeighbor = distMap.get(neighbor);
635
+ if (distSrcToNeighbor) {
636
+ if (dist + weight < distSrcToNeighbor) {
637
+ heap.add({id: dist + weight, val: neighbor});
638
+ preMap.set(neighbor, cur);
639
+ distMap.set(neighbor, dist + weight);
640
+ }
641
+ }
642
+ }
643
+ }
644
+ }
645
+ }
646
+ }
647
+ }
648
+
649
+
650
+ if (getMinDist) {
651
+ distMap.forEach((d, v) => {
652
+ if (v !== srcVertex) {
653
+ if (d < minDist) {
654
+ minDist = d;
655
+ if (genPaths) minDest = v;
656
+ }
657
+ }
658
+ });
659
+ }
660
+
661
+
662
+ if (genPaths) {
663
+ getPaths(minDest);
664
+ }
665
+
666
+
667
+ return {distMap, preMap, seen, paths, minDist, minPath};
668
+ }
669
+
670
+ /**
671
+ * Dijkstra's algorithm only solves the single-source shortest path problem, while the Bellman-Ford algorithm and Floyd-Warshall algorithm can address shortest paths between all pairs of nodes.
672
+ * Dijkstra's algorithm is suitable for graphs with non-negative edge weights, whereas the Bellman-Ford algorithm and Floyd-Warshall algorithm can handle negative-weight edges.
673
+ * The time complexity of Dijkstra's algorithm and the Bellman-Ford algorithm depends on the size of the graph, while the time complexity of the Floyd-Warshall algorithm is O(V^3), where V is the number of nodes. For dense graphs, Floyd-Warshall might become slower.
674
+ */
675
+
676
+ /**
677
+ * Dijkstra algorithm time: O(logVE) space: O(V + E)
678
+ * Dijkstra's algorithm is used to find the shortest paths from a source node to all other nodes in a graph. Its basic idea is to repeatedly choose the node closest to the source node and update the distances of other nodes using this node as an intermediary. Dijkstra's algorithm requires that the edge weights in the graph are non-negative.
679
+ */
680
+
681
+ abstract getEndsOfEdge(edge: E): [V, V] | null;
682
+
683
+ /**
684
+ * BellmanFord time:O(VE) space:O(V)
685
+ * one to rest pairs
686
+ * The Bellman-Ford algorithm is also used to find the shortest paths from a source node to all other nodes in a graph. Unlike Dijkstra's algorithm, it can handle edge weights that are negative. Its basic idea involves iterative relaxation of all edges for several rounds to gradually approximate the shortest paths. Due to its ability to handle negative-weight edges, the Bellman-Ford algorithm is more flexible in some scenarios.
687
+ * The `bellmanFord` function implements the Bellman-Ford algorithm to find the shortest path from a source vertex to
688
+ * all other vertices in a graph, and optionally detects negative cycles and generates the minimum path.
689
+ * @param {V | VertexId} src - The `src` parameter is the source vertex from which the Bellman-Ford algorithm will
690
+ * start calculating the shortest paths. It can be either a vertex object or a vertex ID.
691
+ * @param {boolean} [scanNegativeCycle] - A boolean flag indicating whether to scan for negative cycles in the graph.
692
+ * @param {boolean} [getMin] - The `getMin` parameter is a boolean flag that determines whether the algorithm should
693
+ * calculate the minimum distance from the source vertex to all other vertices in the graph. If `getMin` is set to
694
+ * `true`, the algorithm will find the minimum distance and update the `min` variable with the minimum
695
+ * @param {boolean} [genPath] - A boolean flag indicating whether to generate paths for all vertices from the source
696
+ * vertex.
697
+ * @returns The function `bellmanFord` returns an object with the following properties:
698
+ */
699
+ bellmanFord(src: V | VertexId, scanNegativeCycle?: boolean, getMin?: boolean, genPath?: boolean) {
700
+ if (getMin === undefined) getMin = false;
701
+ if (genPath === undefined) genPath = false;
702
+
703
+ const srcVertex = this._getVertex(src);
704
+ const paths: V[][] = [];
705
+ const distMap: Map<V, number> = new Map();
706
+ const preMap: Map<V, V> = new Map(); // predecessor
707
+ let min = Infinity;
708
+ let minPath: V[] = [];
709
+ // TODO
710
+ let hasNegativeCycle: boolean | undefined;
711
+ if (scanNegativeCycle) hasNegativeCycle = false;
712
+ if (!srcVertex) return {hasNegativeCycle, distMap, preMap, paths, min, minPath};
713
+
714
+ const vertices = this._vertices;
715
+ const numOfVertices = vertices.size;
716
+ const edges = this.edgeSet();
717
+ const numOfEdges = edges.length;
718
+
719
+ this._vertices.forEach(vertex => {
720
+ distMap.set(vertex, Infinity);
721
+ });
722
+
723
+ distMap.set(srcVertex, 0);
724
+
725
+ for (let i = 1; i < numOfVertices; ++i) {
726
+ for (let j = 0; j < numOfEdges; ++j) {
727
+ const ends = this.getEndsOfEdge(edges[j]);
728
+ if (ends) {
729
+ const [s, d] = ends;
730
+ const weight = edges[j].weight;
731
+ const sWeight = distMap.get(s);
732
+ const dWeight = distMap.get(d);
733
+ if (sWeight !== undefined && dWeight !== undefined) {
734
+ if (distMap.get(s) !== Infinity && sWeight + weight < dWeight) {
735
+ distMap.set(d, sWeight + weight);
736
+ genPath && preMap.set(d, s);
737
+ }
738
+ }
739
+ }
740
+ }
741
+ }
742
+
743
+ let minDest: V | null = null;
744
+ if (getMin) {
745
+ distMap.forEach((d, v) => {
746
+ if (v !== srcVertex) {
747
+ if (d < min) {
748
+ min = d;
749
+ if (genPath) minDest = v;
750
+ }
751
+ }
752
+ });
753
+ }
754
+
755
+ if (genPath) {
756
+ for (const vertex of vertices) {
757
+ const vertexOrId = vertex[1];
758
+ if (vertexOrId instanceof AbstractVertex) {
759
+ const path: V[] = [vertexOrId];
760
+ let parent = preMap.get(vertexOrId);
761
+ while (parent !== undefined) {
762
+ path.push(parent);
763
+ parent = preMap.get(parent);
764
+ }
765
+ const reversed = path.reverse();
766
+ if (vertex[1] === minDest) minPath = reversed;
767
+ paths.push(reversed);
768
+ }
769
+ }
770
+ }
771
+
772
+ for (let j = 0; j < numOfEdges; ++j) {
773
+ const ends = this.getEndsOfEdge(edges[j]);
774
+ if (ends) {
775
+ const [s] = ends;
776
+ const weight = edges[j].weight;
777
+ const sWeight = distMap.get(s);
778
+ if (sWeight) {
779
+ if (sWeight !== Infinity && sWeight + weight < sWeight) hasNegativeCycle = true;
780
+ }
781
+ }
782
+ }
783
+
784
+ return {hasNegativeCycle, distMap, preMap, paths, min, minPath};
785
+ }
786
+
787
+ /**
788
+ * BellmanFord time:O(VE) space:O(V)
789
+ * one to rest pairs
790
+ * The Bellman-Ford algorithm is also used to find the shortest paths from a source node to all other nodes in a graph. Unlike Dijkstra's algorithm, it can handle edge weights that are negative. Its basic idea involves iterative relaxation of all edges for several rounds to gradually approximate the shortest paths. Due to its ability to handle negative-weight edges, the Bellman-Ford algorithm is more flexible in some scenarios.
791
+ * The `bellmanFord` function implements the Bellman-Ford algorithm to find the shortest path from a source vertex to
792
+ */
793
+
794
+ /**
795
+ * Floyd algorithm time: O(V^3) space: O(V^2), not support graph with negative weight cycle
796
+ * all pairs
797
+ * The Floyd-Warshall algorithm is used to find the shortest paths between all pairs of nodes in a graph. It employs dynamic programming to compute the shortest paths from any node to any other node. The Floyd-Warshall algorithm's advantage lies in its ability to handle graphs with negative-weight edges, and it can simultaneously compute shortest paths between any two nodes.
798
+ * The function implements the Floyd-Warshall algorithm to find the shortest path between all pairs of vertices in a
799
+ * graph.
800
+ * @returns The function `floyd()` returns an object with two properties: `costs` and `predecessor`. The `costs`
801
+ * property is a 2D array of numbers representing the shortest path costs between vertices in a graph. The
802
+ * `predecessor` property is a 2D array of vertices (or `null`) representing the predecessor vertices in the shortest
803
+ * path between vertices in the
804
+ */
805
+ floyd(): { costs: number[][], predecessor: (V | null)[][] } {
806
+ const idAndVertices = [...this._vertices];
807
+ const n = idAndVertices.length;
808
+
809
+ const costs: number[][] = [];
810
+ const predecessor: (V | null)[][] = [];
811
+ // successors
812
+
813
+ for (let i = 0; i < n; i++) {
814
+ costs[i] = [];
815
+ predecessor[i] = [];
816
+ for (let j = 0; j < n; j++) {
817
+ predecessor[i][j] = null;
818
+ }
819
+ }
820
+
821
+ for (let i = 0; i < n; i++) {
822
+ for (let j = 0; j < n; j++) {
823
+ costs[i][j] = this.getEdge(idAndVertices[i][1], idAndVertices[j][1])?.weight || Infinity;
824
+ }
825
+ }
826
+
827
+ for (let k = 0; k < n; k++) {
828
+ for (let i = 0; i < n; i++) {
829
+ for (let j = 0; j < n; j++) {
830
+ if (costs[i][j] > costs[i][k] + costs[k][j]) {
831
+ costs[i][j] = costs[i][k] + costs[k][j];
832
+ predecessor[i][j] = idAndVertices[k][1];
833
+ }
834
+ }
835
+ }
836
+ }
837
+ return {costs, predecessor};
838
+
839
+ }
840
+
841
+ /**
842
+ * Floyd algorithm time: O(V^3) space: O(V^2), not support graph with negative weight cycle
843
+ * all pairs
844
+ * The Floyd-Warshall algorithm is used to find the shortest paths between all pairs of nodes in a graph. It employs dynamic programming to compute the shortest paths from any node to any other node. The Floyd-Warshall algorithm's advantage lies in its ability to handle graphs with negative-weight edges, and it can simultaneously compute shortest paths between any two nodes.
845
+ */
846
+
847
+ /**
848
+ * Tarjan is an algorithm based on DFS,which is used to solve the connectivity problem of graphs.
849
+ * Tarjan can find cycles in directed or undirected graph
850
+ * Tarjan can find the articulation points and bridges(critical edges) of undirected graphs in linear time,
851
+ * Tarjan solve the bi-connected components of undirected graphs;
852
+ * Tarjan can find the SSC(strongly connected components), articulation points, and bridges of directed graphs.
853
+ * The `tarjan` function is used to perform various graph analysis tasks such as finding articulation points, bridges,
854
+ * strongly connected components (SCCs), and cycles in a graph.
855
+ * @param {boolean} [needArticulationPoints] - A boolean value indicating whether or not to calculate and return the
856
+ * articulation points in the graph. Articulation points are the vertices in a graph whose removal would increase the
857
+ * number of connected components in the graph.
858
+ * @param {boolean} [needBridges] - A boolean flag indicating whether the algorithm should find and return the bridges
859
+ * (edges whose removal would increase the number of connected components in the graph).
860
+ * @param {boolean} [needSCCs] - A boolean value indicating whether the Strongly Connected Components (SCCs) of the
861
+ * graph are needed. If set to true, the function will calculate and return the SCCs of the graph. If set to false, the
862
+ * SCCs will not be calculated or returned.
863
+ * @param {boolean} [needCycles] - A boolean flag indicating whether the algorithm should find cycles in the graph. If
864
+ * set to true, the algorithm will return a map of cycles, where the keys are the low values of the SCCs and the values
865
+ * are arrays of vertices that form cycles within the SCCs.
866
+ * @returns The function `tarjan` returns an object with the following properties:
867
+ */
868
+ tarjan(needArticulationPoints?: boolean, needBridges?: boolean, needSCCs?: boolean, needCycles?: boolean) {
869
+ // !! in undirected graph we will not let child visit parent when DFS
870
+ // !! articulation point(in DFS search tree not in graph): (cur !== root && cur.has(child)) && (low(child) >= dfn(cur)) || (cur === root && cur.children() >= 2)
871
+ // !! bridge: low(child) > dfn(cur)
872
+
873
+ const defaultConfig = false;
874
+ if (needArticulationPoints === undefined) needArticulationPoints = defaultConfig;
875
+ if (needBridges === undefined) needBridges = defaultConfig;
876
+ if (needSCCs === undefined) needSCCs = defaultConfig;
877
+ if (needCycles === undefined) needCycles = defaultConfig;
878
+
879
+ const dfnMap: Map<V, number> = new Map();
880
+ const lowMap: Map<V, number> = new Map();
881
+ const vertices = this._vertices;
882
+ vertices.forEach(v => {
883
+ dfnMap.set(v, -1);
884
+ lowMap.set(v, Infinity);
885
+ });
886
+
887
+ const [root] = vertices.values();
888
+
889
+ const articulationPoints: V[] = [];
890
+ const bridges: E[] = [];
891
+ let dfn = 0;
892
+ const dfs = (cur: V, parent: V | null) => {
893
+ dfn++;
894
+ dfnMap.set(cur, dfn);
895
+ lowMap.set(cur, dfn);
896
+
897
+ const neighbors = this.getNeighbors(cur);
898
+ let childCount = 0; // child in DFS tree not child in graph
899
+ for (const neighbor of neighbors) {
900
+ if (neighbor !== parent) {
901
+ if (dfnMap.get(neighbor) === -1) {
902
+ childCount++;
903
+ dfs(neighbor, cur);
904
+ }
905
+ const childLow = lowMap.get(neighbor);
906
+ const curLow = lowMap.get(cur);
907
+ // TODO after no-non-null-assertion not ensure the logic
908
+ if (curLow !== undefined && childLow !== undefined) {
909
+ lowMap.set(cur, Math.min(curLow, childLow));
910
+ }
911
+ const curFromMap = dfnMap.get(cur);
912
+ if (childLow !== undefined && curFromMap !== undefined) {
913
+ if (needArticulationPoints) {
914
+ if ((cur === root && childCount >= 2) || ((cur !== root) && (childLow >= curFromMap))) {
915
+ // todo not ensure the logic if (cur === root && childCount >= 2 || ((cur !== root) && (childLow >= curFromMap))) {
916
+ articulationPoints.push(cur);
917
+ }
918
+ }
919
+
920
+ if (needBridges) {
921
+ if (childLow > curFromMap) {
922
+ const edgeCurToNeighbor = this.getEdge(cur, neighbor);
923
+ if (edgeCurToNeighbor) {
924
+ bridges.push(edgeCurToNeighbor);
925
+ }
926
+ }
927
+ }
928
+ }
929
+ }
930
+ }
931
+
932
+ };
933
+
934
+ dfs(root, null);
935
+
936
+ let SCCs: Map<number, V[]> = new Map();
937
+
938
+ const getSCCs = () => {
939
+ const SCCs: Map<number, V[]> = new Map();
940
+ lowMap.forEach((low, vertex) => {
941
+ if (!SCCs.has(low)) {
942
+ SCCs.set(low, [vertex]);
943
+ } else {
944
+ SCCs.get(low)?.push(vertex);
945
+ }
946
+ });
947
+ return SCCs;
948
+ };
949
+
950
+ if (needSCCs) {
951
+ SCCs = getSCCs();
952
+ }
953
+
954
+ const cycles: Map<number, V[]> = new Map();
955
+ if (needCycles) {
956
+ let SCCs: Map<number, V[]> = new Map();
957
+ if (SCCs.size < 1) {
958
+ SCCs = getSCCs();
959
+ }
960
+
961
+ SCCs.forEach((SCC, low) => {
962
+ if (SCC.length > 1) {
963
+ cycles.set(low, SCC);
964
+ }
965
+ });
966
+ }
967
+
968
+ return {dfnMap, lowMap, bridges, articulationPoints, SCCs, cycles};
969
+ }
970
+
971
+
972
+ /**--- start find cycles --- */
973
+
974
+ protected _setVertices(value: Map<VertexId, V>) {
975
+ this._vertices = value;
976
+ }
977
+
978
+
979
+ // unionFind() {}
980
+
981
+ /**--- end find cycles --- */
982
+
983
+
984
+ // Minimum Spanning Tree
985
+ }