min-heap-typed 1.40.0-rc → 1.40.0

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 (347) hide show
  1. package/.dependency-cruiser.js +422 -422
  2. package/.eslintrc.js +59 -59
  3. package/.prettierrc.js +14 -14
  4. package/README.md +20 -3
  5. package/coverage/clover.xml +11 -7
  6. package/coverage/coverage-final.json +95 -1
  7. package/coverage/coverage-summary.json +59 -2
  8. package/coverage/lcov-report/base.css +278 -99
  9. package/coverage/lcov-report/index.html +69 -65
  10. package/coverage/lcov-report/index.ts.html +36 -35
  11. package/coverage/lcov-report/sorter.js +15 -5
  12. package/dist/data-structures/binary-tree/avl-tree.d.ts +106 -0
  13. package/dist/data-structures/binary-tree/avl-tree.js +347 -0
  14. package/dist/data-structures/binary-tree/binary-indexed-tree.d.ts +149 -0
  15. package/dist/data-structures/binary-tree/binary-indexed-tree.js +269 -0
  16. package/dist/data-structures/binary-tree/binary-tree.d.ts +355 -0
  17. package/dist/data-structures/binary-tree/binary-tree.js +1115 -0
  18. package/dist/data-structures/binary-tree/bst.d.ts +167 -0
  19. package/dist/data-structures/binary-tree/bst.js +512 -0
  20. package/dist/data-structures/binary-tree/index.d.ts +7 -0
  21. package/dist/data-structures/binary-tree/index.js +23 -0
  22. package/dist/data-structures/binary-tree/rb-tree.d.ts +11 -0
  23. package/dist/data-structures/binary-tree/rb-tree.js +21 -0
  24. package/dist/data-structures/binary-tree/segment-tree.d.ts +67 -0
  25. package/dist/data-structures/binary-tree/segment-tree.js +180 -0
  26. package/dist/data-structures/binary-tree/tree-multiset.d.ts +126 -0
  27. package/dist/data-structures/binary-tree/tree-multiset.js +355 -0
  28. package/dist/data-structures/graph/abstract-graph.d.ts +313 -0
  29. package/dist/data-structures/graph/abstract-graph.js +884 -0
  30. package/dist/data-structures/graph/directed-graph.d.ts +194 -0
  31. package/dist/data-structures/graph/directed-graph.js +404 -0
  32. package/dist/data-structures/graph/index.d.ts +4 -0
  33. package/dist/data-structures/graph/index.js +20 -0
  34. package/dist/data-structures/graph/map-graph.d.ts +73 -0
  35. package/dist/data-structures/graph/map-graph.js +93 -0
  36. package/dist/data-structures/graph/undirected-graph.d.ts +120 -0
  37. package/dist/data-structures/graph/undirected-graph.js +239 -0
  38. package/dist/data-structures/hash/coordinate-map.d.ts +44 -0
  39. package/dist/data-structures/hash/coordinate-map.js +62 -0
  40. package/dist/data-structures/hash/coordinate-set.d.ts +36 -0
  41. package/dist/data-structures/hash/coordinate-set.js +52 -0
  42. package/dist/data-structures/hash/hash-map.d.ts +50 -0
  43. package/dist/data-structures/hash/hash-map.js +153 -0
  44. package/dist/data-structures/hash/hash-table.d.ts +103 -0
  45. package/dist/data-structures/hash/hash-table.js +236 -0
  46. package/dist/data-structures/hash/index.d.ts +6 -0
  47. package/dist/data-structures/hash/index.js +22 -0
  48. package/dist/data-structures/hash/tree-map.d.ts +2 -0
  49. package/dist/data-structures/hash/tree-map.js +6 -0
  50. package/dist/data-structures/hash/tree-set.d.ts +2 -0
  51. package/dist/data-structures/hash/tree-set.js +6 -0
  52. package/dist/data-structures/heap/heap.d.ts +235 -0
  53. package/dist/data-structures/heap/heap.js +515 -0
  54. package/dist/data-structures/heap/index.d.ts +3 -0
  55. package/dist/data-structures/heap/index.js +19 -0
  56. package/dist/data-structures/heap/max-heap.d.ts +15 -0
  57. package/dist/data-structures/heap/max-heap.js +26 -0
  58. package/dist/data-structures/heap/min-heap.d.ts +15 -0
  59. package/dist/data-structures/heap/min-heap.js +26 -0
  60. package/dist/data-structures/index.d.ts +11 -0
  61. package/dist/data-structures/index.js +27 -0
  62. package/dist/data-structures/linked-list/doubly-linked-list.d.ts +253 -0
  63. package/dist/data-structures/linked-list/doubly-linked-list.js +569 -0
  64. package/dist/data-structures/linked-list/index.d.ts +3 -0
  65. package/dist/data-structures/linked-list/index.js +19 -0
  66. package/dist/data-structures/linked-list/singly-linked-list.d.ts +232 -0
  67. package/dist/data-structures/linked-list/singly-linked-list.js +533 -0
  68. package/dist/data-structures/linked-list/skip-linked-list.d.ts +80 -0
  69. package/dist/data-structures/linked-list/skip-linked-list.js +187 -0
  70. package/dist/data-structures/matrix/index.d.ts +4 -0
  71. package/dist/data-structures/matrix/index.js +20 -0
  72. package/dist/data-structures/matrix/matrix.d.ts +21 -0
  73. package/dist/data-structures/matrix/matrix.js +28 -0
  74. package/dist/data-structures/matrix/matrix2d.d.ts +107 -0
  75. package/dist/data-structures/matrix/matrix2d.js +199 -0
  76. package/dist/data-structures/matrix/navigator.d.ts +52 -0
  77. package/dist/data-structures/matrix/navigator.js +106 -0
  78. package/dist/data-structures/matrix/vector2d.d.ts +200 -0
  79. package/dist/data-structures/matrix/vector2d.js +290 -0
  80. package/dist/data-structures/priority-queue/index.d.ts +3 -0
  81. package/dist/data-structures/priority-queue/index.js +19 -0
  82. package/dist/data-structures/priority-queue/max-priority-queue.d.ts +15 -0
  83. package/dist/data-structures/priority-queue/max-priority-queue.js +26 -0
  84. package/dist/data-structures/priority-queue/min-priority-queue.d.ts +15 -0
  85. package/dist/data-structures/priority-queue/min-priority-queue.js +26 -0
  86. package/dist/data-structures/priority-queue/priority-queue.d.ts +15 -0
  87. package/dist/data-structures/priority-queue/priority-queue.js +17 -0
  88. package/dist/data-structures/queue/deque.d.ts +161 -0
  89. package/dist/data-structures/queue/deque.js +264 -0
  90. package/dist/data-structures/queue/index.d.ts +2 -0
  91. package/dist/data-structures/queue/index.js +18 -0
  92. package/dist/data-structures/queue/queue.d.ts +122 -0
  93. package/dist/data-structures/queue/queue.js +187 -0
  94. package/dist/data-structures/stack/index.d.ts +1 -0
  95. package/dist/data-structures/stack/index.js +17 -0
  96. package/dist/data-structures/stack/stack.d.ts +64 -0
  97. package/dist/data-structures/stack/stack.js +94 -0
  98. package/dist/data-structures/tree/index.d.ts +1 -0
  99. package/dist/data-structures/tree/index.js +17 -0
  100. package/dist/data-structures/tree/tree.d.ts +8 -0
  101. package/dist/data-structures/tree/tree.js +40 -0
  102. package/dist/data-structures/trie/index.d.ts +1 -0
  103. package/dist/data-structures/trie/index.js +17 -0
  104. package/dist/data-structures/trie/trie.d.ts +79 -0
  105. package/dist/data-structures/trie/trie.js +251 -0
  106. package/dist/index.d.ts +3 -1
  107. package/dist/index.js +18 -4
  108. package/dist/interfaces/binary-tree.d.ts +7 -0
  109. package/dist/interfaces/binary-tree.js +2 -0
  110. package/dist/interfaces/doubly-linked-list.d.ts +1 -0
  111. package/dist/interfaces/doubly-linked-list.js +2 -0
  112. package/dist/interfaces/graph.d.ts +5 -0
  113. package/dist/interfaces/graph.js +2 -0
  114. package/dist/interfaces/heap.d.ts +1 -0
  115. package/dist/interfaces/heap.js +2 -0
  116. package/dist/interfaces/index.d.ts +8 -0
  117. package/dist/interfaces/index.js +24 -0
  118. package/dist/interfaces/navigator.d.ts +1 -0
  119. package/dist/interfaces/navigator.js +2 -0
  120. package/dist/interfaces/priority-queue.d.ts +1 -0
  121. package/dist/interfaces/priority-queue.js +2 -0
  122. package/dist/interfaces/segment-tree.d.ts +1 -0
  123. package/dist/interfaces/segment-tree.js +2 -0
  124. package/dist/interfaces/singly-linked-list.d.ts +1 -0
  125. package/dist/interfaces/singly-linked-list.js +2 -0
  126. package/dist/types/data-structures/binary-tree/avl-tree.d.ts +4 -0
  127. package/dist/types/data-structures/binary-tree/avl-tree.js +2 -0
  128. package/dist/types/data-structures/binary-tree/binary-indexed-tree.d.ts +1 -0
  129. package/dist/types/data-structures/binary-tree/binary-indexed-tree.js +2 -0
  130. package/dist/types/data-structures/binary-tree/binary-tree.d.ts +29 -0
  131. package/dist/types/data-structures/binary-tree/binary-tree.js +24 -0
  132. package/dist/types/data-structures/binary-tree/bst.d.ts +7 -0
  133. package/dist/types/data-structures/binary-tree/bst.js +2 -0
  134. package/dist/types/data-structures/binary-tree/index.d.ts +6 -0
  135. package/dist/types/data-structures/binary-tree/index.js +22 -0
  136. package/dist/types/data-structures/binary-tree/rb-tree.d.ts +8 -0
  137. package/dist/types/data-structures/binary-tree/rb-tree.js +8 -0
  138. package/dist/types/data-structures/binary-tree/segment-tree.d.ts +1 -0
  139. package/dist/types/data-structures/binary-tree/segment-tree.js +2 -0
  140. package/dist/types/data-structures/binary-tree/tree-multiset.d.ts +4 -0
  141. package/dist/types/data-structures/binary-tree/tree-multiset.js +2 -0
  142. package/dist/types/data-structures/graph/abstract-graph.d.ts +10 -0
  143. package/dist/types/data-structures/graph/abstract-graph.js +2 -0
  144. package/dist/types/data-structures/graph/directed-graph.d.ts +6 -0
  145. package/dist/types/data-structures/graph/directed-graph.js +9 -0
  146. package/dist/types/data-structures/graph/index.d.ts +3 -0
  147. package/dist/types/data-structures/graph/index.js +19 -0
  148. package/dist/types/data-structures/graph/map-graph.d.ts +1 -0
  149. package/dist/types/data-structures/graph/map-graph.js +2 -0
  150. package/dist/types/data-structures/graph/undirected-graph.d.ts +1 -0
  151. package/dist/types/data-structures/graph/undirected-graph.js +2 -0
  152. package/dist/types/data-structures/hash/coordinate-map.d.ts +1 -0
  153. package/dist/types/data-structures/hash/coordinate-map.js +2 -0
  154. package/dist/types/data-structures/hash/coordinate-set.d.ts +1 -0
  155. package/dist/types/data-structures/hash/coordinate-set.js +2 -0
  156. package/dist/types/data-structures/hash/hash-map.d.ts +1 -0
  157. package/dist/types/data-structures/hash/hash-map.js +2 -0
  158. package/dist/types/data-structures/hash/hash-table.d.ts +1 -0
  159. package/dist/types/data-structures/hash/hash-table.js +2 -0
  160. package/dist/types/data-structures/hash/index.d.ts +1 -0
  161. package/dist/types/data-structures/hash/index.js +2 -0
  162. package/dist/types/data-structures/hash/tree-map.d.ts +1 -0
  163. package/dist/types/data-structures/hash/tree-map.js +2 -0
  164. package/dist/types/data-structures/hash/tree-set.d.ts +1 -0
  165. package/dist/types/data-structures/hash/tree-set.js +2 -0
  166. package/dist/types/data-structures/heap/heap.d.ts +1 -0
  167. package/dist/types/data-structures/heap/heap.js +2 -0
  168. package/dist/types/data-structures/heap/index.d.ts +1 -0
  169. package/dist/types/data-structures/heap/index.js +17 -0
  170. package/dist/types/data-structures/heap/max-heap.d.ts +1 -0
  171. package/dist/types/data-structures/heap/max-heap.js +2 -0
  172. package/dist/types/data-structures/heap/min-heap.d.ts +1 -0
  173. package/dist/types/data-structures/heap/min-heap.js +2 -0
  174. package/dist/types/data-structures/index.d.ts +11 -0
  175. package/dist/types/data-structures/index.js +27 -0
  176. package/dist/types/data-structures/linked-list/doubly-linked-list.d.ts +1 -0
  177. package/dist/types/data-structures/linked-list/doubly-linked-list.js +2 -0
  178. package/dist/types/data-structures/linked-list/index.d.ts +2 -0
  179. package/dist/types/data-structures/linked-list/index.js +18 -0
  180. package/dist/types/data-structures/linked-list/singly-linked-list.d.ts +1 -0
  181. package/dist/types/data-structures/linked-list/singly-linked-list.js +2 -0
  182. package/dist/types/data-structures/linked-list/skip-linked-list.d.ts +1 -0
  183. package/dist/types/data-structures/linked-list/skip-linked-list.js +2 -0
  184. package/dist/types/data-structures/matrix/index.d.ts +1 -0
  185. package/dist/types/data-structures/matrix/index.js +17 -0
  186. package/dist/types/data-structures/matrix/matrix.d.ts +1 -0
  187. package/dist/types/data-structures/matrix/matrix.js +2 -0
  188. package/dist/types/data-structures/matrix/matrix2d.d.ts +1 -0
  189. package/dist/types/data-structures/matrix/matrix2d.js +2 -0
  190. package/dist/types/data-structures/matrix/navigator.d.ts +14 -0
  191. package/dist/types/data-structures/matrix/navigator.js +2 -0
  192. package/dist/types/data-structures/matrix/vector2d.d.ts +1 -0
  193. package/dist/types/data-structures/matrix/vector2d.js +2 -0
  194. package/dist/types/data-structures/priority-queue/index.d.ts +3 -0
  195. package/dist/types/data-structures/priority-queue/index.js +19 -0
  196. package/dist/types/data-structures/priority-queue/max-priority-queue.d.ts +1 -0
  197. package/dist/types/data-structures/priority-queue/max-priority-queue.js +2 -0
  198. package/dist/types/data-structures/priority-queue/min-priority-queue.d.ts +1 -0
  199. package/dist/types/data-structures/priority-queue/min-priority-queue.js +2 -0
  200. package/dist/types/data-structures/priority-queue/priority-queue.d.ts +1 -0
  201. package/dist/types/data-structures/priority-queue/priority-queue.js +2 -0
  202. package/dist/types/data-structures/queue/deque.d.ts +1 -0
  203. package/dist/types/data-structures/queue/deque.js +2 -0
  204. package/dist/types/data-structures/queue/index.d.ts +2 -0
  205. package/dist/types/data-structures/queue/index.js +18 -0
  206. package/dist/types/data-structures/queue/queue.d.ts +1 -0
  207. package/dist/types/data-structures/queue/queue.js +2 -0
  208. package/dist/types/data-structures/stack/index.d.ts +1 -0
  209. package/dist/types/data-structures/stack/index.js +17 -0
  210. package/dist/types/data-structures/stack/stack.d.ts +1 -0
  211. package/dist/types/data-structures/stack/stack.js +2 -0
  212. package/dist/types/data-structures/tree/index.d.ts +1 -0
  213. package/dist/types/data-structures/tree/index.js +17 -0
  214. package/dist/types/data-structures/tree/tree.d.ts +1 -0
  215. package/dist/types/data-structures/tree/tree.js +2 -0
  216. package/dist/types/data-structures/trie/index.d.ts +1 -0
  217. package/dist/types/data-structures/trie/index.js +17 -0
  218. package/dist/types/data-structures/trie/trie.d.ts +1 -0
  219. package/dist/types/data-structures/trie/trie.js +2 -0
  220. package/dist/types/helpers.d.ts +8 -0
  221. package/dist/types/helpers.js +9 -0
  222. package/dist/types/index.d.ts +3 -0
  223. package/dist/types/index.js +19 -0
  224. package/dist/types/utils/index.d.ts +2 -0
  225. package/dist/types/utils/index.js +18 -0
  226. package/dist/types/utils/utils.d.ts +7 -0
  227. package/dist/types/utils/utils.js +2 -0
  228. package/dist/types/utils/validate-type.d.ts +19 -0
  229. package/dist/types/utils/validate-type.js +2 -0
  230. package/dist/utils/index.d.ts +1 -0
  231. package/dist/utils/index.js +17 -0
  232. package/dist/utils/utils.d.ts +20 -0
  233. package/dist/utils/utils.js +73 -0
  234. package/jest.config.js +6 -6
  235. package/package.json +2 -2
  236. package/src/data-structures/binary-tree/avl-tree.ts +350 -0
  237. package/src/data-structures/binary-tree/binary-indexed-tree.ts +306 -0
  238. package/src/data-structures/binary-tree/binary-tree.ts +1262 -0
  239. package/src/data-structures/binary-tree/bst.ts +522 -0
  240. package/src/data-structures/binary-tree/index.ts +7 -0
  241. package/src/data-structures/binary-tree/rb-tree.ts +358 -0
  242. package/src/data-structures/binary-tree/segment-tree.ts +190 -0
  243. package/src/data-structures/binary-tree/tree-multiset.ts +379 -0
  244. package/src/data-structures/graph/abstract-graph.ts +1000 -0
  245. package/src/data-structures/graph/directed-graph.ts +449 -0
  246. package/src/data-structures/graph/index.ts +4 -0
  247. package/src/data-structures/graph/map-graph.ts +106 -0
  248. package/src/data-structures/graph/undirected-graph.ts +259 -0
  249. package/src/data-structures/hash/coordinate-map.ts +63 -0
  250. package/src/data-structures/hash/coordinate-set.ts +52 -0
  251. package/src/data-structures/hash/hash-map.ts +185 -0
  252. package/src/data-structures/hash/hash-table.ts +268 -0
  253. package/src/data-structures/hash/index.ts +6 -0
  254. package/src/data-structures/hash/tree-map.ts +2 -0
  255. package/src/data-structures/hash/tree-set.ts +2 -0
  256. package/src/data-structures/heap/heap.ts +589 -0
  257. package/src/data-structures/heap/index.ts +3 -0
  258. package/src/data-structures/heap/max-heap.ts +26 -0
  259. package/src/data-structures/heap/min-heap.ts +26 -0
  260. package/src/data-structures/index.ts +11 -0
  261. package/src/data-structures/linked-list/doubly-linked-list.ts +605 -0
  262. package/src/data-structures/linked-list/index.ts +3 -0
  263. package/src/data-structures/linked-list/singly-linked-list.ts +576 -0
  264. package/src/data-structures/linked-list/skip-linked-list.ts +221 -0
  265. package/src/data-structures/matrix/index.ts +4 -0
  266. package/src/data-structures/matrix/matrix.ts +27 -0
  267. package/src/data-structures/matrix/matrix2d.ts +211 -0
  268. package/src/data-structures/matrix/navigator.ts +121 -0
  269. package/src/data-structures/matrix/vector2d.ts +315 -0
  270. package/src/data-structures/priority-queue/index.ts +3 -0
  271. package/src/data-structures/priority-queue/max-priority-queue.ts +25 -0
  272. package/src/data-structures/priority-queue/min-priority-queue.ts +25 -0
  273. package/src/data-structures/priority-queue/priority-queue.ts +16 -0
  274. package/src/data-structures/queue/deque.ts +282 -0
  275. package/src/data-structures/queue/index.ts +2 -0
  276. package/src/data-structures/queue/queue.ts +209 -0
  277. package/src/data-structures/stack/index.ts +1 -0
  278. package/src/data-structures/stack/stack.ts +102 -0
  279. package/src/data-structures/tree/index.ts +1 -0
  280. package/src/data-structures/tree/tree.ts +41 -0
  281. package/src/data-structures/trie/index.ts +1 -0
  282. package/src/data-structures/trie/trie.ts +262 -0
  283. package/src/index.ts +4 -1
  284. package/src/interfaces/binary-tree.ts +10 -0
  285. package/src/interfaces/doubly-linked-list.ts +1 -0
  286. package/src/interfaces/graph.ts +7 -0
  287. package/src/interfaces/heap.ts +1 -0
  288. package/src/interfaces/index.ts +8 -0
  289. package/src/interfaces/navigator.ts +1 -0
  290. package/src/interfaces/priority-queue.ts +1 -0
  291. package/src/interfaces/segment-tree.ts +1 -0
  292. package/src/interfaces/singly-linked-list.ts +1 -0
  293. package/src/types/data-structures/binary-tree/avl-tree.ts +5 -0
  294. package/src/types/data-structures/binary-tree/binary-indexed-tree.ts +1 -0
  295. package/src/types/data-structures/binary-tree/binary-tree.ts +31 -0
  296. package/src/types/data-structures/binary-tree/bst.ts +11 -0
  297. package/src/types/data-structures/binary-tree/index.ts +6 -0
  298. package/src/types/data-structures/binary-tree/rb-tree.ts +8 -0
  299. package/src/types/data-structures/binary-tree/segment-tree.ts +1 -0
  300. package/src/types/data-structures/binary-tree/tree-multiset.ts +6 -0
  301. package/src/types/data-structures/graph/abstract-graph.ts +11 -0
  302. package/src/types/data-structures/graph/directed-graph.ts +8 -0
  303. package/src/types/data-structures/graph/index.ts +3 -0
  304. package/src/types/data-structures/graph/map-graph.ts +1 -0
  305. package/src/types/data-structures/graph/undirected-graph.ts +1 -0
  306. package/src/types/data-structures/hash/coordinate-map.ts +1 -0
  307. package/src/types/data-structures/hash/coordinate-set.ts +1 -0
  308. package/src/types/data-structures/hash/hash-map.ts +1 -0
  309. package/src/types/data-structures/hash/hash-table.ts +1 -0
  310. package/src/types/data-structures/hash/index.ts +1 -0
  311. package/src/types/data-structures/hash/tree-map.ts +1 -0
  312. package/src/types/data-structures/hash/tree-set.ts +1 -0
  313. package/src/types/data-structures/heap/heap.ts +1 -0
  314. package/src/types/data-structures/heap/index.ts +1 -0
  315. package/src/types/data-structures/heap/max-heap.ts +1 -0
  316. package/src/types/data-structures/heap/min-heap.ts +1 -0
  317. package/src/types/data-structures/index.ts +11 -0
  318. package/src/types/data-structures/linked-list/doubly-linked-list.ts +1 -0
  319. package/src/types/data-structures/linked-list/index.ts +2 -0
  320. package/src/types/data-structures/linked-list/singly-linked-list.ts +1 -0
  321. package/src/types/data-structures/linked-list/skip-linked-list.ts +1 -0
  322. package/src/types/data-structures/matrix/index.ts +1 -0
  323. package/src/types/data-structures/matrix/matrix.ts +1 -0
  324. package/src/types/data-structures/matrix/matrix2d.ts +1 -0
  325. package/src/types/data-structures/matrix/navigator.ts +14 -0
  326. package/src/types/data-structures/matrix/vector2d.ts +1 -0
  327. package/src/types/data-structures/priority-queue/index.ts +3 -0
  328. package/src/types/data-structures/priority-queue/max-priority-queue.ts +1 -0
  329. package/src/types/data-structures/priority-queue/min-priority-queue.ts +1 -0
  330. package/src/types/data-structures/priority-queue/priority-queue.ts +1 -0
  331. package/src/types/data-structures/queue/deque.ts +1 -0
  332. package/src/types/data-structures/queue/index.ts +2 -0
  333. package/src/types/data-structures/queue/queue.ts +1 -0
  334. package/src/types/data-structures/stack/index.ts +1 -0
  335. package/src/types/data-structures/stack/stack.ts +1 -0
  336. package/src/types/data-structures/tree/index.ts +1 -0
  337. package/src/types/data-structures/tree/tree.ts +1 -0
  338. package/src/types/data-structures/trie/index.ts +1 -0
  339. package/src/types/data-structures/trie/trie.ts +1 -0
  340. package/src/types/helpers.ts +11 -0
  341. package/src/types/index.ts +3 -0
  342. package/src/types/utils/index.ts +2 -0
  343. package/src/types/utils/utils.ts +6 -0
  344. package/src/types/utils/validate-type.ts +35 -0
  345. package/src/utils/index.ts +1 -0
  346. package/src/utils/utils.ts +86 -0
  347. package/tsconfig.json +1 -2
@@ -0,0 +1,1000 @@
1
+ /**
2
+ * data-structure-typed
3
+ *
4
+ * @author Kirk Qi
5
+ * @copyright Copyright (c) 2022 Kirk Qi <qilinaus@gmail.com>
6
+ * @license MIT License
7
+ */
8
+ import {arrayRemove, uuidV4} from '../../utils';
9
+ import {PriorityQueue} from '../priority-queue';
10
+ import type {DijkstraResult, VertexKey} from '../../types';
11
+ import {IGraph} from '../../interfaces';
12
+ import {Queue} from '../queue';
13
+
14
+ export abstract class AbstractVertex<V = any> {
15
+ key: VertexKey;
16
+ value: V | undefined;
17
+
18
+ /**
19
+ * The function is a protected constructor that takes an key and an optional value as parameters.
20
+ * @param {VertexKey} key - The `key` parameter is of type `VertexKey` and represents the identifier of the vertex. It is
21
+ * used to uniquely identify the vertex object.
22
+ * @param {V} [value] - The parameter "value" is an optional parameter of type V. It is used to assign a value to the
23
+ * vertex. If no value is provided, it will be set to undefined.
24
+ */
25
+ protected constructor(key: VertexKey, value?: V) {
26
+ this.key = key;
27
+ this.value = value;
28
+ }
29
+
30
+ }
31
+
32
+ export abstract class AbstractEdge<E = any> {
33
+ value: E | undefined;
34
+ weight: number;
35
+
36
+ /**
37
+ * The above function is a protected constructor that initializes the weight, value, and hash code properties of an
38
+ * object.
39
+ * @param {number} [weight] - The `weight` parameter is an optional number that represents the weight of the object. If
40
+ * a value is provided, it will be assigned to the `_weight` property. If no value is provided, the default value of 1
41
+ * will be assigned.
42
+ * @param {VO} [value] - The `value` parameter is of type `VO`, which means it can be any type. It is an optional parameter,
43
+ * meaning it can be omitted when creating an instance of the class.
44
+ */
45
+ protected constructor(weight?: number, value?: E) {
46
+ this.weight = weight !== undefined ? weight : 1;
47
+ this.value = value;
48
+ this._hashCode = uuidV4();
49
+ }
50
+
51
+ protected _hashCode: string;
52
+
53
+ get hashCode(): string {
54
+ return this._hashCode;
55
+ }
56
+
57
+ /**
58
+ * 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.
59
+ * 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.
60
+ */
61
+ }
62
+
63
+ export abstract class AbstractGraph<
64
+ V = any,
65
+ E = any,
66
+ VO extends AbstractVertex<V> = AbstractVertex<V>,
67
+ EO extends AbstractEdge<E> = AbstractEdge<E>
68
+ > implements IGraph<V, E, VO, EO> {
69
+ protected _vertices: Map<VertexKey, VO> = new Map<VertexKey, VO>();
70
+
71
+ get vertices(): Map<VertexKey, VO> {
72
+ return this._vertices;
73
+ }
74
+
75
+ /**
76
+ * 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.
77
+ * 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.
78
+ * @param key
79
+ * @param value
80
+ */
81
+ abstract createVertex(key: VertexKey, value?: V): VO;
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 value
90
+ */
91
+ abstract createEdge(srcOrV1: VertexKey, destOrV2: VertexKey, weight?: number, value?: E): EO;
92
+
93
+ abstract deleteEdge(edge: EO): EO | null;
94
+
95
+ abstract getEdge(srcOrKey: VO | VertexKey, destOrKey: VO | VertexKey): EO | null;
96
+
97
+ abstract degreeOf(vertexOrKey: VO | VertexKey): number;
98
+
99
+ abstract edgeSet(): EO[];
100
+
101
+ abstract edgesOf(vertexOrKey: VO | VertexKey): EO[];
102
+
103
+ abstract getNeighbors(vertexOrKey: VO | VertexKey): VO[];
104
+
105
+ abstract getEndsOfEdge(edge: EO): [VO, VO] | null;
106
+
107
+ /**
108
+ * The function "getVertex" returns the vertex with the specified ID or null if it doesn't exist.
109
+ * @param {VertexKey} vertexKey - The `vertexKey` parameter is the identifier of the vertex that you want to retrieve from
110
+ * the `_vertices` map.
111
+ * @returns The method `getVertex` returns the vertex with the specified `vertexKey` if it exists in the `_vertices`
112
+ * map. If the vertex does not exist, it returns `null`.
113
+ */
114
+ getVertex(vertexKey: VertexKey): VO | null {
115
+ return this._vertices.get(vertexKey) || null;
116
+ }
117
+
118
+ /**
119
+ * The function checks if a vertex exists in a graph.
120
+ * @param {VO | VertexKey} vertexOrKey - The parameter `vertexOrKey` can be either a vertex object (`VO`) or a vertex ID
121
+ * (`VertexKey`).
122
+ * @returns a boolean value.
123
+ */
124
+ hasVertex(vertexOrKey: VO | VertexKey): boolean {
125
+ return this._vertices.has(this._getVertexKey(vertexOrKey));
126
+ }
127
+
128
+ addVertex(vertex: VO): boolean;
129
+
130
+ addVertex(key: VertexKey, value?: V): boolean;
131
+
132
+ addVertex(keyOrVertex: VertexKey | VO, value?: V): boolean {
133
+ if (keyOrVertex instanceof AbstractVertex) {
134
+ return this._addVertexOnly(keyOrVertex);
135
+ } else {
136
+ const newVertex = this.createVertex(keyOrVertex, value);
137
+ return this._addVertexOnly(newVertex);
138
+ }
139
+ }
140
+
141
+ /**
142
+ * The `deleteVertex` function removes a vertex from a graph by its ID or by the vertex object itself.
143
+ * @param {VO | VertexKey} vertexOrKey - The parameter `vertexOrKey` can be either a vertex object (`VO`) or a vertex ID
144
+ * (`VertexKey`).
145
+ * @returns The method is returning a boolean value.
146
+ */
147
+ deleteVertex(vertexOrKey: VO | VertexKey): boolean {
148
+ const vertexKey = this._getVertexKey(vertexOrKey);
149
+ return this._vertices.delete(vertexKey);
150
+ }
151
+
152
+ /**
153
+ * The function removes all vertices from a graph and returns a boolean indicating if any vertices were removed.
154
+ * @param {VO[] | VertexKey[]} vertices - The `vertices` parameter can be either an array of vertices (`VO[]`) or an array
155
+ * of vertex IDs (`VertexKey[]`).
156
+ * @returns a boolean value. It returns true if at least one vertex was successfully removed, and false if no vertices
157
+ * were removed.
158
+ */
159
+ removeManyVertices(vertices: VO[] | VertexKey[]): boolean {
160
+ const removed: boolean[] = [];
161
+ for (const v of vertices) {
162
+ removed.push(this.deleteVertex(v));
163
+ }
164
+ return removed.length > 0;
165
+ }
166
+
167
+ /**
168
+ * The function checks if there is an edge between two vertices and returns a boolean value indicating the result.
169
+ * @param {VertexKey | VO} v1 - The parameter v1 can be either a VertexKey or a VO. A VertexKey represents the unique
170
+ * identifier of a vertex in a graph, while VO represents the type of the vertex object itself.
171
+ * @param {VertexKey | VO} v2 - The parameter `v2` represents the second vertex in the edge. It can be either a
172
+ * `VertexKey` or a `VO` type, which represents the type of the vertex.
173
+ * @returns A boolean value is being returned.
174
+ */
175
+ hasEdge(v1: VertexKey | VO, v2: VertexKey | VO): boolean {
176
+ const edge = this.getEdge(v1, v2);
177
+ return !!edge;
178
+ }
179
+
180
+ addEdge(edge: EO): boolean;
181
+
182
+ addEdge(src: VO | VertexKey, dest: VO | VertexKey, weight?: number, value?: E): boolean;
183
+
184
+ addEdge(srcOrEdge: VO | VertexKey | EO, dest?: VO | VertexKey, weight?: number, value?: E): boolean {
185
+ if (srcOrEdge instanceof AbstractEdge) {
186
+ return this._addEdgeOnly(srcOrEdge);
187
+ } else {
188
+ if (dest instanceof AbstractVertex || typeof dest === 'string' || typeof dest === 'number') {
189
+ if (!(this.hasVertex(srcOrEdge) && this.hasVertex(dest))) return false;
190
+ if (srcOrEdge instanceof AbstractVertex) srcOrEdge = srcOrEdge.key;
191
+ if (dest instanceof AbstractVertex) dest = dest.key;
192
+ const newEdge = this.createEdge(srcOrEdge, dest, weight, value);
193
+ return this._addEdgeOnly(newEdge);
194
+ } else {
195
+ throw new Error('dest must be a Vertex or vertex key while srcOrEdge is an Edge');
196
+ }
197
+ }
198
+ }
199
+
200
+ /**
201
+ * The function sets the weight of an edge between two vertices in a graph.
202
+ * @param {VertexKey | VO} srcOrKey - The `srcOrKey` parameter can be either a `VertexKey` or a `VO` object. It represents
203
+ * the source vertex of the edge.
204
+ * @param {VertexKey | VO} destOrKey - The `destOrKey` parameter represents the destination vertex of the edge. It can be
205
+ * either a `VertexKey` or a vertex object `VO`.
206
+ * @param {number} weight - The weight parameter represents the weight of the edge between the source vertex (srcOrKey)
207
+ * and the destination vertex (destOrKey).
208
+ * @returns a boolean value. If the edge exists between the source and destination vertices, the function will update
209
+ * the weight of the edge and return true. If the edge does not exist, the function will return false.
210
+ */
211
+ setEdgeWeight(srcOrKey: VertexKey | VO, destOrKey: VertexKey | VO, weight: number): boolean {
212
+ const edge = this.getEdge(srcOrKey, destOrKey);
213
+ if (edge) {
214
+ edge.weight = weight;
215
+ return true;
216
+ } else {
217
+ return false;
218
+ }
219
+ }
220
+
221
+ /**
222
+ * The function `getAllPathsBetween` finds all paths between two vertices in a graph using depth-first search.
223
+ * @param {VO | VertexKey} v1 - The parameter `v1` represents either a vertex object (`VO`) or a vertex ID (`VertexKey`).
224
+ * It is the starting vertex for finding paths.
225
+ * @param {VO | VertexKey} v2 - The parameter `v2` represents either a vertex object (`VO`) or a vertex ID (`VertexKey`).
226
+ * @returns The function `getAllPathsBetween` returns an array of arrays of vertices (`VO[][]`).
227
+ */
228
+ getAllPathsBetween(v1: VO | VertexKey, v2: VO | VertexKey): VO[][] {
229
+ const paths: VO[][] = [];
230
+ const vertex1 = this._getVertex(v1);
231
+ const vertex2 = this._getVertex(v2);
232
+ if (!(vertex1 && vertex2)) {
233
+ return [];
234
+ }
235
+
236
+ const dfs = (cur: VO, dest: VO, visiting: Map<VO, boolean>, path: VO[]) => {
237
+ visiting.set(cur, true);
238
+
239
+ if (cur === dest) {
240
+ paths.push([vertex1, ...path]);
241
+ }
242
+
243
+ const neighbors = this.getNeighbors(cur);
244
+ for (const neighbor of neighbors) {
245
+ if (!visiting.get(neighbor)) {
246
+ path.push(neighbor);
247
+ dfs(neighbor, dest, visiting, path);
248
+ arrayRemove(path, (vertex: VO) => vertex === neighbor);
249
+ }
250
+ }
251
+
252
+ visiting.set(cur, false);
253
+ };
254
+
255
+ dfs(vertex1, vertex2, new Map<VO, boolean>(), []);
256
+ return paths;
257
+ }
258
+
259
+ /**
260
+ * The function calculates the sum of weights along a given path.
261
+ * @param {VO[]} path - An array of vertices (VO) representing a path in a graph.
262
+ * @returns The function `getPathSumWeight` returns the sum of the weights of the edges in the given path.
263
+ */
264
+ getPathSumWeight(path: VO[]): number {
265
+ let sum = 0;
266
+ for (let i = 0; i < path.length; i++) {
267
+ sum += this.getEdge(path[i], path[i + 1])?.weight || 0;
268
+ }
269
+ return sum;
270
+ }
271
+
272
+ /**
273
+ * The function `getMinCostBetween` calculates the minimum cost between two vertices in a graph, either based on edge
274
+ * weights or using a breadth-first search algorithm.
275
+ * @param {VO | VertexKey} v1 - The parameter `v1` represents the starting vertex or its ID.
276
+ * @param {VO | VertexKey} v2 - The parameter `v2` represents the destination vertex or its ID. It is the vertex to which
277
+ * you want to find the minimum cost or weight from the source vertex `v1`.
278
+ * @param {boolean} [isWeight] - isWeight is an optional parameter that indicates whether the graph edges have weights.
279
+ * If isWeight is set to true, the function will calculate the minimum cost between v1 and v2 based on the weights of
280
+ * the edges. If isWeight is set to false or not provided, the function will calculate the
281
+ * @returns The function `getMinCostBetween` returns a number representing the minimum cost between two vertices (`v1`
282
+ * and `v2`). If the `isWeight` parameter is `true`, it calculates the minimum weight among all paths between the
283
+ * vertices. If `isWeight` is `false` or not provided, it uses a breadth-first search (BFS) algorithm to calculate the
284
+ * minimum number of
285
+ */
286
+ getMinCostBetween(v1: VO | VertexKey, v2: VO | VertexKey, isWeight?: boolean): number | null {
287
+ if (isWeight === undefined) isWeight = false;
288
+
289
+ if (isWeight) {
290
+ const allPaths = this.getAllPathsBetween(v1, v2);
291
+ let min = Infinity;
292
+ for (const path of allPaths) {
293
+ min = Math.min(this.getPathSumWeight(path), min);
294
+ }
295
+ return min;
296
+ } else {
297
+ // BFS
298
+ const vertex2 = this._getVertex(v2);
299
+ const vertex1 = this._getVertex(v1);
300
+ if (!(vertex1 && vertex2)) {
301
+ return null;
302
+ }
303
+
304
+ const visited: Map<VO, boolean> = new Map();
305
+ const queue = new Queue<VO>([vertex1]);
306
+ visited.set(vertex1, true);
307
+ let cost = 0;
308
+ while (queue.size > 0) {
309
+ for (let i = 0; i < queue.size; i++) {
310
+ const cur = queue.shift();
311
+ if (cur === vertex2) {
312
+ return cost;
313
+ }
314
+ // TODO consider optimizing to AbstractGraph
315
+ if (cur !== undefined) {
316
+ const neighbors = this.getNeighbors(cur);
317
+ for (const neighbor of neighbors) {
318
+ if (!visited.has(neighbor)) {
319
+ visited.set(neighbor, true);
320
+ queue.push(neighbor);
321
+ }
322
+ }
323
+ }
324
+ }
325
+ cost++;
326
+ }
327
+ return null;
328
+ }
329
+ }
330
+
331
+ /**
332
+ * The function `getMinPathBetween` returns the minimum path between two vertices in a graph, either based on weight or
333
+ * using a breadth-first search algorithm.
334
+ * @param {VO | VertexKey} v1 - The parameter `v1` represents the starting vertex of the path. It can be either a vertex
335
+ * object (`VO`) or a vertex ID (`VertexKey`).
336
+ * @param {VO | VertexKey} v2 - VO | VertexKey - The second vertex or vertex ID between which we want to find the minimum
337
+ * path.
338
+ * @param {boolean} [isWeight] - A boolean flag indicating whether to consider the weight of edges in finding the
339
+ * minimum path. If set to true, the function will use Dijkstra's algorithm to find the minimum weighted path. If set
340
+ * to false, the function will use breadth-first search (BFS) to find the minimum path.
341
+ * @returns The function `getMinPathBetween` returns an array of vertices (`VO[]`) representing the minimum path between
342
+ * two vertices (`v1` and `v2`). If there is no path between the vertices, it returns `null`.
343
+ */
344
+ getMinPathBetween(v1: VO | VertexKey, v2: VO | VertexKey, isWeight?: boolean): VO[] | null {
345
+ if (isWeight === undefined) isWeight = false;
346
+
347
+ if (isWeight) {
348
+ const allPaths = this.getAllPathsBetween(v1, v2);
349
+ let min = Infinity;
350
+ let minIndex = -1;
351
+ let index = 0;
352
+ for (const path of allPaths) {
353
+ const pathSumWeight = this.getPathSumWeight(path);
354
+ if (pathSumWeight < min) {
355
+ min = pathSumWeight;
356
+ minIndex = index;
357
+ }
358
+ index++;
359
+ }
360
+ return allPaths[minIndex] || null;
361
+ } else {
362
+ // BFS
363
+ let minPath: VO[] = [];
364
+ const vertex1 = this._getVertex(v1);
365
+ const vertex2 = this._getVertex(v2);
366
+ if (!(vertex1 && vertex2)) {
367
+ return [];
368
+ }
369
+
370
+ const dfs = (cur: VO, dest: VO, visiting: Map<VO, boolean>, path: VO[]) => {
371
+ visiting.set(cur, true);
372
+
373
+ if (cur === dest) {
374
+ minPath = [vertex1, ...path];
375
+ return;
376
+ }
377
+
378
+ const neighbors = this.getNeighbors(cur);
379
+ for (const neighbor of neighbors) {
380
+ if (!visiting.get(neighbor)) {
381
+ path.push(neighbor);
382
+ dfs(neighbor, dest, visiting, path);
383
+ arrayRemove(path, (vertex: VO) => vertex === neighbor);
384
+ }
385
+ }
386
+
387
+ visiting.set(cur, false);
388
+ };
389
+
390
+ dfs(vertex1, vertex2, new Map<VO, boolean>(), []);
391
+ return minPath;
392
+ }
393
+ }
394
+
395
+ /**
396
+ * Dijkstra algorithm time: O(VE) space: O(VO + EO)
397
+ * /
398
+
399
+ /**
400
+ * Dijkstra algorithm time: O(VE) space: O(VO + EO)
401
+ * The function `dijkstraWithoutHeap` implements Dijkstra's algorithm to find the shortest path between two vertices in
402
+ * a graph without using a heap data structure.
403
+ * @param {VO | VertexKey} src - The source vertex from which to start the Dijkstra's algorithm. It can be either a
404
+ * vertex object or a vertex ID.
405
+ * @param {VO | VertexKey | null} [dest] - The `dest` parameter in the `dijkstraWithoutHeap` function is an optional
406
+ * parameter that specifies the destination vertex for the Dijkstra algorithm. It can be either a vertex object or its
407
+ * identifier. If no destination is provided, the value is set to `null`.
408
+ * @param {boolean} [getMinDist] - The `getMinDist` parameter is a boolean flag that determines whether the minimum
409
+ * distance from the source vertex to the destination vertex should be calculated and returned in the result. If
410
+ * `getMinDist` is set to `true`, the `minDist` property in the result will contain the minimum distance
411
+ * @param {boolean} [genPaths] - The `genPaths` parameter is a boolean flag that determines whether or not to generate
412
+ * paths in the Dijkstra algorithm. If `genPaths` is set to `true`, the algorithm will calculate and return the
413
+ * shortest paths from the source vertex to all other vertices in the graph. If `genPaths
414
+ * @returns The function `dijkstraWithoutHeap` returns an object of type `DijkstraResult<VO>`.
415
+ */
416
+ dijkstraWithoutHeap(
417
+ src: VO | VertexKey,
418
+ dest?: VO | VertexKey | null,
419
+ getMinDist?: boolean,
420
+ genPaths?: boolean
421
+ ): DijkstraResult<VO> {
422
+ if (getMinDist === undefined) getMinDist = false;
423
+ if (genPaths === undefined) genPaths = false;
424
+
425
+ if (dest === undefined) dest = null;
426
+ let minDist = Infinity;
427
+ let minDest: VO | null = null;
428
+ let minPath: VO[] = [];
429
+ const paths: VO[][] = [];
430
+
431
+ const vertices = this._vertices;
432
+ const distMap: Map<VO, number> = new Map();
433
+ const seen: Set<VO> = new Set();
434
+ const preMap: Map<VO, VO | null> = new Map(); // predecessor
435
+ const srcVertex = this._getVertex(src);
436
+
437
+ const destVertex = dest ? this._getVertex(dest) : null;
438
+
439
+ if (!srcVertex) {
440
+ return null;
441
+ }
442
+
443
+ for (const vertex of vertices) {
444
+ const vertexOrKey = vertex[1];
445
+ if (vertexOrKey instanceof AbstractVertex) distMap.set(vertexOrKey, Infinity);
446
+ }
447
+ distMap.set(srcVertex, 0);
448
+ preMap.set(srcVertex, null);
449
+
450
+ const getMinOfNoSeen = () => {
451
+ let min = Infinity;
452
+ let minV: VO | null = null;
453
+ for (const [key, value] of distMap) {
454
+ if (!seen.has(key)) {
455
+ if (value < min) {
456
+ min = value;
457
+ minV = key;
458
+ }
459
+ }
460
+ }
461
+ return minV;
462
+ };
463
+
464
+ const getPaths = (minV: VO | null) => {
465
+ for (const vertex of vertices) {
466
+ const vertexOrKey = vertex[1];
467
+
468
+ if (vertexOrKey instanceof AbstractVertex) {
469
+ const path: VO[] = [vertexOrKey];
470
+ let parent = preMap.get(vertexOrKey);
471
+ while (parent) {
472
+ path.push(parent);
473
+ parent = preMap.get(parent);
474
+ }
475
+ const reversed = path.reverse();
476
+ if (vertex[1] === minV) minPath = reversed;
477
+ paths.push(reversed);
478
+ }
479
+ }
480
+ };
481
+
482
+ for (let i = 1; i < vertices.size; i++) {
483
+ const cur = getMinOfNoSeen();
484
+ if (cur) {
485
+ seen.add(cur);
486
+ if (destVertex && destVertex === cur) {
487
+ if (getMinDist) {
488
+ minDist = distMap.get(destVertex) || Infinity;
489
+ }
490
+ if (genPaths) {
491
+ getPaths(destVertex);
492
+ }
493
+ return {distMap, preMap, seen, paths, minDist, minPath};
494
+ }
495
+ const neighbors = this.getNeighbors(cur);
496
+ for (const neighbor of neighbors) {
497
+ if (!seen.has(neighbor)) {
498
+ const edge = this.getEdge(cur, neighbor);
499
+ if (edge) {
500
+ const curFromMap = distMap.get(cur);
501
+ const neighborFromMap = distMap.get(neighbor);
502
+ // TODO after no-non-null-assertion not ensure the logic
503
+ if (curFromMap !== undefined && neighborFromMap !== undefined) {
504
+ if (edge.weight + curFromMap < neighborFromMap) {
505
+ distMap.set(neighbor, edge.weight + curFromMap);
506
+ preMap.set(neighbor, cur);
507
+ }
508
+ }
509
+ }
510
+ }
511
+ }
512
+ }
513
+ }
514
+
515
+ getMinDist &&
516
+ distMap.forEach((d, v) => {
517
+ if (v !== srcVertex) {
518
+ if (d < minDist) {
519
+ minDist = d;
520
+ if (genPaths) minDest = v;
521
+ }
522
+ }
523
+ });
524
+
525
+ genPaths && getPaths(minDest);
526
+
527
+ return {distMap, preMap, seen, paths, minDist, minPath};
528
+ }
529
+
530
+ /**
531
+ * Dijkstra algorithm time: O(logVE) space: O(VO + EO)
532
+ *
533
+ * 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.
534
+ * 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.
535
+ * 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(VO^3), where VO is the number of nodes. For dense graphs, Floyd-Warshall might become slower.
536
+ *
537
+ * /
538
+
539
+ /**
540
+ * 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.
541
+ * The `dijkstra` function implements Dijkstra's algorithm to find the shortest path between a source vertex and an
542
+ * optional destination vertex, and optionally returns the minimum distance, the paths, and other information.
543
+ * @param {VO | VertexKey} src - The `src` parameter represents the source vertex from which the Dijkstra algorithm will
544
+ * start. It can be either a vertex object or a vertex ID.
545
+ * @param {VO | VertexKey | null} [dest] - The `dest` parameter is the destination vertex or vertex ID. It specifies the
546
+ * vertex to which the shortest path is calculated from the source vertex. If no destination is provided, the algorithm
547
+ * will calculate the shortest paths to all other vertices from the source vertex.
548
+ * @param {boolean} [getMinDist] - The `getMinDist` parameter is a boolean flag that determines whether the minimum
549
+ * distance from the source vertex to the destination vertex should be calculated and returned in the result. If
550
+ * `getMinDist` is set to `true`, the `minDist` property in the result will contain the minimum distance
551
+ * @param {boolean} [genPaths] - The `genPaths` parameter is a boolean flag that determines whether or not to generate
552
+ * paths in the Dijkstra algorithm. If `genPaths` is set to `true`, the algorithm will calculate and return the
553
+ * shortest paths from the source vertex to all other vertices in the graph. If `genPaths
554
+ * @returns The function `dijkstra` returns an object of type `DijkstraResult<VO>`.
555
+ */
556
+ dijkstra(
557
+ src: VO | VertexKey,
558
+ dest?: VO | VertexKey | null,
559
+ getMinDist?: boolean,
560
+ genPaths?: boolean
561
+ ): DijkstraResult<VO> {
562
+ if (getMinDist === undefined) getMinDist = false;
563
+ if (genPaths === undefined) genPaths = false;
564
+
565
+ if (dest === undefined) dest = null;
566
+ let minDist = Infinity;
567
+ let minDest: VO | null = null;
568
+ let minPath: VO[] = [];
569
+ const paths: VO[][] = [];
570
+ const vertices = this._vertices;
571
+ const distMap: Map<VO, number> = new Map();
572
+ const seen: Set<VO> = new Set();
573
+ const preMap: Map<VO, VO | null> = new Map(); // predecessor
574
+
575
+ const srcVertex = this._getVertex(src);
576
+ const destVertex = dest ? this._getVertex(dest) : null;
577
+
578
+ if (!srcVertex) return null;
579
+
580
+ for (const vertex of vertices) {
581
+ const vertexOrKey = vertex[1];
582
+ if (vertexOrKey instanceof AbstractVertex) distMap.set(vertexOrKey, Infinity);
583
+ }
584
+
585
+ const heap = new PriorityQueue<{ key: number; value: VO }>({comparator: (a, b) => a.key - b.key});
586
+ heap.add({key: 0, value: srcVertex});
587
+
588
+ distMap.set(srcVertex, 0);
589
+ preMap.set(srcVertex, null);
590
+
591
+ /**
592
+ * The function `getPaths` retrieves all paths from vertices to a specified minimum vertex.
593
+ * @param {VO | null} minV - The parameter `minV` is of type `VO | null`. It represents the minimum vertex value or
594
+ * null.
595
+ */
596
+ const getPaths = (minV: VO | null) => {
597
+ for (const vertex of vertices) {
598
+ const vertexOrKey = vertex[1];
599
+ if (vertexOrKey instanceof AbstractVertex) {
600
+ const path: VO[] = [vertexOrKey];
601
+ let parent = preMap.get(vertexOrKey);
602
+ while (parent) {
603
+ path.push(parent);
604
+ parent = preMap.get(parent);
605
+ }
606
+ const reversed = path.reverse();
607
+ if (vertex[1] === minV) minPath = reversed;
608
+ paths.push(reversed);
609
+ }
610
+ }
611
+ };
612
+
613
+ while (heap.size > 0) {
614
+ const curHeapNode = heap.poll();
615
+ const dist = curHeapNode?.key;
616
+ const cur = curHeapNode?.value;
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({key: dist + weight, value: neighbor});
638
+ preMap.set(neighbor, cur);
639
+ distMap.set(neighbor, dist + weight);
640
+ }
641
+ }
642
+ }
643
+ }
644
+ }
645
+ }
646
+ }
647
+ }
648
+
649
+ if (getMinDist) {
650
+ distMap.forEach((d, v) => {
651
+ if (v !== srcVertex) {
652
+ if (d < minDist) {
653
+ minDist = d;
654
+ if (genPaths) minDest = v;
655
+ }
656
+ }
657
+ });
658
+ }
659
+
660
+ if (genPaths) {
661
+ getPaths(minDest);
662
+ }
663
+
664
+ return {distMap, preMap, seen, paths, minDist, minPath};
665
+ }
666
+
667
+ /**
668
+ * BellmanFord time:O(VE) space:O(VO)
669
+ * one to rest pairs
670
+ * /
671
+
672
+ /**
673
+ * BellmanFord time:O(VE) space:O(VO)
674
+ * one to rest pairs
675
+ * 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.
676
+ * The `bellmanFord` function implements the Bellman-Ford algorithm to find the shortest path from a source vertex to
677
+ * all other vertices in a graph, and optionally detects negative cycles and generates the minimum path.
678
+ * @param {VO | VertexKey} src - The `src` parameter is the source vertex from which the Bellman-Ford algorithm will
679
+ * start calculating the shortest paths. It can be either a vertex object or a vertex ID.
680
+ * @param {boolean} [scanNegativeCycle] - A boolean flag indicating whether to scan for negative cycles in the graph.
681
+ * @param {boolean} [getMin] - The `getMin` parameter is a boolean flag that determines whether the algorithm should
682
+ * calculate the minimum distance from the source vertex to all other vertices in the graph. If `getMin` is set to
683
+ * `true`, the algorithm will find the minimum distance and update the `min` variable with the minimum
684
+ * @param {boolean} [genPath] - A boolean flag indicating whether to generate paths for all vertices from the source
685
+ * vertex.
686
+ * @returns The function `bellmanFord` returns an object with the following properties:
687
+ */
688
+ bellmanFord(src: VO | VertexKey, scanNegativeCycle?: boolean, getMin?: boolean, genPath?: boolean) {
689
+ if (getMin === undefined) getMin = false;
690
+ if (genPath === undefined) genPath = false;
691
+
692
+ const srcVertex = this._getVertex(src);
693
+ const paths: VO[][] = [];
694
+ const distMap: Map<VO, number> = new Map();
695
+ const preMap: Map<VO, VO> = new Map(); // predecessor
696
+ let min = Infinity;
697
+ let minPath: VO[] = [];
698
+ // TODO
699
+ let hasNegativeCycle: boolean | undefined;
700
+ if (scanNegativeCycle) hasNegativeCycle = false;
701
+ if (!srcVertex) return {hasNegativeCycle, distMap, preMap, paths, min, minPath};
702
+
703
+ const vertices = this._vertices;
704
+ const numOfVertices = vertices.size;
705
+ const edges = this.edgeSet();
706
+ const numOfEdges = edges.length;
707
+
708
+ this._vertices.forEach(vertex => {
709
+ distMap.set(vertex, Infinity);
710
+ });
711
+
712
+ distMap.set(srcVertex, 0);
713
+
714
+ for (let i = 1; i < numOfVertices; ++i) {
715
+ for (let j = 0; j < numOfEdges; ++j) {
716
+ const ends = this.getEndsOfEdge(edges[j]);
717
+ if (ends) {
718
+ const [s, d] = ends;
719
+ const weight = edges[j].weight;
720
+ const sWeight = distMap.get(s);
721
+ const dWeight = distMap.get(d);
722
+ if (sWeight !== undefined && dWeight !== undefined) {
723
+ if (distMap.get(s) !== Infinity && sWeight + weight < dWeight) {
724
+ distMap.set(d, sWeight + weight);
725
+ genPath && preMap.set(d, s);
726
+ }
727
+ }
728
+ }
729
+ }
730
+ }
731
+
732
+ let minDest: VO | null = null;
733
+ if (getMin) {
734
+ distMap.forEach((d, v) => {
735
+ if (v !== srcVertex) {
736
+ if (d < min) {
737
+ min = d;
738
+ if (genPath) minDest = v;
739
+ }
740
+ }
741
+ });
742
+ }
743
+
744
+ if (genPath) {
745
+ for (const vertex of vertices) {
746
+ const vertexOrKey = vertex[1];
747
+ if (vertexOrKey instanceof AbstractVertex) {
748
+ const path: VO[] = [vertexOrKey];
749
+ let parent = preMap.get(vertexOrKey);
750
+ while (parent !== undefined) {
751
+ path.push(parent);
752
+ parent = preMap.get(parent);
753
+ }
754
+ const reversed = path.reverse();
755
+ if (vertex[1] === minDest) minPath = reversed;
756
+ paths.push(reversed);
757
+ }
758
+ }
759
+ }
760
+
761
+ for (let j = 0; j < numOfEdges; ++j) {
762
+ const ends = this.getEndsOfEdge(edges[j]);
763
+ if (ends) {
764
+ const [s] = ends;
765
+ const weight = edges[j].weight;
766
+ const sWeight = distMap.get(s);
767
+ if (sWeight) {
768
+ if (sWeight !== Infinity && sWeight + weight < sWeight) hasNegativeCycle = true;
769
+ }
770
+ }
771
+ }
772
+
773
+ return {hasNegativeCycle, distMap, preMap, paths, min, minPath};
774
+ }
775
+
776
+ /**
777
+ * Dijkstra algorithm time: O(logVE) space: O(VO + EO)
778
+ * /
779
+
780
+ /**
781
+ * Dijkstra algorithm time: O(logVE) space: O(VO + EO)
782
+ * 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.
783
+ */
784
+
785
+ /**
786
+ * BellmanFord time:O(VE) space:O(VO)
787
+ * one to rest pairs
788
+ * 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.
789
+ * The `bellmanFord` function implements the Bellman-Ford algorithm to find the shortest path from a source vertex to
790
+ */
791
+
792
+ /**
793
+ * Floyd algorithm time: O(VO^3) space: O(VO^2), not support graph with negative weight cycle
794
+ * all pairs
795
+ * 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.
796
+ */
797
+
798
+ /**
799
+ * Floyd algorithm time: O(VO^3) space: O(VO^2), not support graph with negative weight cycle
800
+ * all pairs
801
+ * /
802
+
803
+ /**
804
+ * Floyd algorithm time: O(VO^3) space: O(VO^2), not support graph with negative weight cycle
805
+ * all pairs
806
+ * 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.
807
+ * The function implements the Floyd-Warshall algorithm to find the shortest path between all pairs of vertices in a
808
+ * graph.
809
+ * @returns The function `floyd()` returns an object with two properties: `costs` and `predecessor`. The `costs`
810
+ * property is a 2D array of numbers representing the shortest path costs between vertices in a graph. The
811
+ * `predecessor` property is a 2D array of vertices (or `null`) representing the predecessor vertices in the shortest
812
+ * path between vertices in the
813
+ */
814
+ floyd(): { costs: number[][]; predecessor: (VO | null)[][] } {
815
+ const idAndVertices = [...this._vertices];
816
+ const n = idAndVertices.length;
817
+
818
+ const costs: number[][] = [];
819
+ const predecessor: (VO | null)[][] = [];
820
+ // successors
821
+
822
+ for (let i = 0; i < n; i++) {
823
+ costs[i] = [];
824
+ predecessor[i] = [];
825
+ for (let j = 0; j < n; j++) {
826
+ predecessor[i][j] = null;
827
+ }
828
+ }
829
+
830
+ for (let i = 0; i < n; i++) {
831
+ for (let j = 0; j < n; j++) {
832
+ costs[i][j] = this.getEdge(idAndVertices[i][1], idAndVertices[j][1])?.weight || Infinity;
833
+ }
834
+ }
835
+
836
+ for (let k = 0; k < n; k++) {
837
+ for (let i = 0; i < n; i++) {
838
+ for (let j = 0; j < n; j++) {
839
+ if (costs[i][j] > costs[i][k] + costs[k][j]) {
840
+ costs[i][j] = costs[i][k] + costs[k][j];
841
+ predecessor[i][j] = idAndVertices[k][1];
842
+ }
843
+ }
844
+ }
845
+ }
846
+ return {costs, predecessor};
847
+ }
848
+
849
+ /**
850
+ * Tarjan is an algorithm based on dfs,which is used to solve the connectivity problem of graphs.
851
+ * Tarjan can find cycles in directed or undirected graph
852
+ * Tarjan can find the articulation points and bridges(critical edges) of undirected graphs in linear time,
853
+ * Tarjan solve the bi-connected components of undirected graphs;
854
+ * Tarjan can find the SSC(strongly connected components), articulation points, and bridges of directed graphs.
855
+ * /
856
+
857
+ /**
858
+ * Tarjan is an algorithm based on dfs,which is used to solve the connectivity problem of graphs.
859
+ * Tarjan can find cycles in directed or undirected graph
860
+ * Tarjan can find the articulation points and bridges(critical edges) of undirected graphs in linear time,
861
+ * Tarjan solve the bi-connected components of undirected graphs;
862
+ * Tarjan can find the SSC(strongly connected components), articulation points, and bridges of directed graphs.
863
+ * The `tarjan` function is used to perform various graph analysis tasks such as finding articulation points, bridges,
864
+ * strongly connected components (SCCs), and cycles in a graph.
865
+ * @param {boolean} [needArticulationPoints] - A boolean value indicating whether or not to calculate and return the
866
+ * articulation points in the graph. Articulation points are the vertices in a graph whose removal would increase the
867
+ * number of connected components in the graph.
868
+ * @param {boolean} [needBridges] - A boolean flag indicating whether the algorithm should find and return the bridges
869
+ * (edges whose removal would increase the number of connected components in the graph).
870
+ * @param {boolean} [needSCCs] - A boolean value indicating whether the Strongly Connected Components (SCCs) of the
871
+ * graph are needed. If set to true, the function will calculate and return the SCCs of the graph. If set to false, the
872
+ * SCCs will not be calculated or returned.
873
+ * @param {boolean} [needCycles] - A boolean flag indicating whether the algorithm should find cycles in the graph. If
874
+ * set to true, the algorithm will return a map of cycles, where the keys are the low values of the SCCs and the values
875
+ * are arrays of vertices that form cycles within the SCCs.
876
+ * @returns The function `tarjan` returns an object with the following properties:
877
+ */
878
+ tarjan(needArticulationPoints?: boolean, needBridges?: boolean, needSCCs?: boolean, needCycles?: boolean) {
879
+ // !! in undirected graph we will not let child visit parent when dfs
880
+ // !! articulation point(in dfs search tree not in graph): (cur !== root && cur.has(child)) && (low(child) >= dfn(cur)) || (cur === root && cur.children() >= 2)
881
+ // !! bridge: low(child) > dfn(cur)
882
+
883
+ const defaultConfig = false;
884
+ if (needArticulationPoints === undefined) needArticulationPoints = defaultConfig;
885
+ if (needBridges === undefined) needBridges = defaultConfig;
886
+ if (needSCCs === undefined) needSCCs = defaultConfig;
887
+ if (needCycles === undefined) needCycles = defaultConfig;
888
+
889
+ const dfnMap: Map<VO, number> = new Map();
890
+ const lowMap: Map<VO, number> = new Map();
891
+ const vertices = this._vertices;
892
+ vertices.forEach(v => {
893
+ dfnMap.set(v, -1);
894
+ lowMap.set(v, Infinity);
895
+ });
896
+
897
+ const [root] = vertices.values();
898
+
899
+ const articulationPoints: VO[] = [];
900
+ const bridges: EO[] = [];
901
+ let dfn = 0;
902
+ const dfs = (cur: VO, parent: VO | null) => {
903
+ dfn++;
904
+ dfnMap.set(cur, dfn);
905
+ lowMap.set(cur, dfn);
906
+
907
+ const neighbors = this.getNeighbors(cur);
908
+ let childCount = 0; // child in dfs tree not child in graph
909
+ for (const neighbor of neighbors) {
910
+ if (neighbor !== parent) {
911
+ if (dfnMap.get(neighbor) === -1) {
912
+ childCount++;
913
+ dfs(neighbor, cur);
914
+ }
915
+ const childLow = lowMap.get(neighbor);
916
+ const curLow = lowMap.get(cur);
917
+ // TODO after no-non-null-assertion not ensure the logic
918
+ if (curLow !== undefined && childLow !== undefined) {
919
+ lowMap.set(cur, Math.min(curLow, childLow));
920
+ }
921
+ const curFromMap = dfnMap.get(cur);
922
+ if (childLow !== undefined && curFromMap !== undefined) {
923
+ if (needArticulationPoints) {
924
+ if ((cur === root && childCount >= 2) || (cur !== root && childLow >= curFromMap)) {
925
+ // todo not ensure the logic if (cur === root && childCount >= 2 || ((cur !== root) && (childLow >= curFromMap))) {
926
+ articulationPoints.push(cur);
927
+ }
928
+ }
929
+
930
+ if (needBridges) {
931
+ if (childLow > curFromMap) {
932
+ const edgeCurToNeighbor = this.getEdge(cur, neighbor);
933
+ if (edgeCurToNeighbor) {
934
+ bridges.push(edgeCurToNeighbor);
935
+ }
936
+ }
937
+ }
938
+ }
939
+ }
940
+ }
941
+ };
942
+
943
+ dfs(root, null);
944
+
945
+ let SCCs: Map<number, VO[]> = new Map();
946
+
947
+ const getSCCs = () => {
948
+ const SCCs: Map<number, VO[]> = new Map();
949
+ lowMap.forEach((low, vertex) => {
950
+ if (!SCCs.has(low)) {
951
+ SCCs.set(low, [vertex]);
952
+ } else {
953
+ SCCs.get(low)?.push(vertex);
954
+ }
955
+ });
956
+ return SCCs;
957
+ };
958
+
959
+ if (needSCCs) {
960
+ SCCs = getSCCs();
961
+ }
962
+
963
+ const cycles: Map<number, VO[]> = new Map();
964
+ if (needCycles) {
965
+ let SCCs: Map<number, VO[]> = new Map();
966
+ if (SCCs.size < 1) {
967
+ SCCs = getSCCs();
968
+ }
969
+
970
+ SCCs.forEach((SCC, low) => {
971
+ if (SCC.length > 1) {
972
+ cycles.set(low, SCC);
973
+ }
974
+ });
975
+ }
976
+
977
+ return {dfnMap, lowMap, bridges, articulationPoints, SCCs, cycles};
978
+ }
979
+
980
+ protected abstract _addEdgeOnly(edge: EO): boolean;
981
+
982
+ protected _addVertexOnly(newVertex: VO): boolean {
983
+ if (this.hasVertex(newVertex)) {
984
+ return false;
985
+ // throw (new Error('Duplicated vertex key is not allowed'));
986
+ }
987
+ this._vertices.set(newVertex.key, newVertex);
988
+ return true;
989
+ }
990
+
991
+ protected _getVertex(vertexOrKey: VertexKey | VO): VO | null {
992
+ const vertexKey = this._getVertexKey(vertexOrKey);
993
+ return this._vertices.get(vertexKey) || null;
994
+ }
995
+
996
+ protected _getVertexKey(vertexOrKey: VO | VertexKey): VertexKey {
997
+ return vertexOrKey instanceof AbstractVertex ? vertexOrKey.key : vertexOrKey;
998
+ }
999
+
1000
+ }