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