avl-tree-typed 2.0.5 → 2.1.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.
- package/dist/common/index.js +1 -1
- package/dist/constants/index.js +1 -1
- package/dist/data-structures/base/iterable-element-base.d.ts +186 -83
- package/dist/data-structures/base/iterable-element-base.js +149 -107
- package/dist/data-structures/base/iterable-entry-base.d.ts +95 -119
- package/dist/data-structures/base/iterable-entry-base.js +59 -116
- package/dist/data-structures/base/linear-base.d.ts +250 -192
- package/dist/data-structures/base/linear-base.js +137 -274
- package/dist/data-structures/binary-tree/avl-tree-counter.d.ts +126 -158
- package/dist/data-structures/binary-tree/avl-tree-counter.js +171 -205
- package/dist/data-structures/binary-tree/avl-tree-multi-map.d.ts +100 -69
- package/dist/data-structures/binary-tree/avl-tree-multi-map.js +135 -87
- package/dist/data-structures/binary-tree/avl-tree.d.ts +138 -149
- package/dist/data-structures/binary-tree/avl-tree.js +208 -195
- package/dist/data-structures/binary-tree/binary-tree.d.ts +476 -632
- package/dist/data-structures/binary-tree/binary-tree.js +598 -869
- package/dist/data-structures/binary-tree/bst.d.ts +258 -306
- package/dist/data-structures/binary-tree/bst.js +505 -481
- package/dist/data-structures/binary-tree/red-black-tree.d.ts +107 -179
- package/dist/data-structures/binary-tree/red-black-tree.js +114 -209
- package/dist/data-structures/binary-tree/tree-counter.d.ts +132 -154
- package/dist/data-structures/binary-tree/tree-counter.js +172 -203
- package/dist/data-structures/binary-tree/tree-multi-map.d.ts +72 -69
- package/dist/data-structures/binary-tree/tree-multi-map.js +105 -85
- package/dist/data-structures/graph/abstract-graph.d.ts +238 -233
- package/dist/data-structures/graph/abstract-graph.js +267 -237
- package/dist/data-structures/graph/directed-graph.d.ts +108 -224
- package/dist/data-structures/graph/directed-graph.js +146 -233
- package/dist/data-structures/graph/map-graph.d.ts +49 -55
- package/dist/data-structures/graph/map-graph.js +56 -59
- package/dist/data-structures/graph/undirected-graph.d.ts +103 -146
- package/dist/data-structures/graph/undirected-graph.js +129 -149
- package/dist/data-structures/hash/hash-map.d.ts +164 -338
- package/dist/data-structures/hash/hash-map.js +270 -457
- package/dist/data-structures/heap/heap.d.ts +214 -289
- package/dist/data-structures/heap/heap.js +340 -349
- package/dist/data-structures/heap/max-heap.d.ts +11 -47
- package/dist/data-structures/heap/max-heap.js +11 -66
- package/dist/data-structures/heap/min-heap.d.ts +12 -47
- package/dist/data-structures/heap/min-heap.js +11 -66
- package/dist/data-structures/linked-list/doubly-linked-list.d.ts +231 -347
- package/dist/data-structures/linked-list/doubly-linked-list.js +368 -494
- package/dist/data-structures/linked-list/singly-linked-list.d.ts +261 -310
- package/dist/data-structures/linked-list/singly-linked-list.js +447 -466
- package/dist/data-structures/linked-list/skip-linked-list.d.ts +0 -107
- package/dist/data-structures/linked-list/skip-linked-list.js +0 -100
- package/dist/data-structures/priority-queue/max-priority-queue.d.ts +12 -56
- package/dist/data-structures/priority-queue/max-priority-queue.js +11 -78
- package/dist/data-structures/priority-queue/min-priority-queue.d.ts +11 -57
- package/dist/data-structures/priority-queue/min-priority-queue.js +10 -79
- package/dist/data-structures/priority-queue/priority-queue.d.ts +2 -61
- package/dist/data-structures/priority-queue/priority-queue.js +8 -83
- package/dist/data-structures/queue/deque.d.ts +227 -254
- package/dist/data-structures/queue/deque.js +309 -348
- package/dist/data-structures/queue/queue.d.ts +180 -201
- package/dist/data-structures/queue/queue.js +265 -248
- package/dist/data-structures/stack/stack.d.ts +124 -102
- package/dist/data-structures/stack/stack.js +181 -125
- package/dist/data-structures/trie/trie.d.ts +164 -165
- package/dist/data-structures/trie/trie.js +189 -172
- package/dist/interfaces/binary-tree.d.ts +56 -6
- package/dist/interfaces/graph.d.ts +16 -0
- package/dist/types/data-structures/base/base.d.ts +1 -1
- package/dist/types/data-structures/graph/abstract-graph.d.ts +4 -0
- package/dist/types/utils/utils.d.ts +1 -0
- package/dist/utils/number.js +1 -2
- package/dist/utils/utils.d.ts +1 -1
- package/dist/utils/utils.js +9 -8
- package/package.json +15 -15
- package/src/data-structures/base/iterable-element-base.ts +238 -115
- package/src/data-structures/base/iterable-entry-base.ts +96 -120
- package/src/data-structures/base/linear-base.ts +271 -277
- package/src/data-structures/binary-tree/avl-tree-counter.ts +198 -216
- package/src/data-structures/binary-tree/avl-tree-multi-map.ts +192 -101
- package/src/data-structures/binary-tree/avl-tree.ts +239 -206
- package/src/data-structures/binary-tree/binary-tree.ts +664 -893
- package/src/data-structures/binary-tree/bst.ts +568 -570
- package/src/data-structures/binary-tree/red-black-tree.ts +161 -222
- package/src/data-structures/binary-tree/tree-counter.ts +199 -218
- package/src/data-structures/binary-tree/tree-multi-map.ts +131 -97
- package/src/data-structures/graph/abstract-graph.ts +339 -264
- package/src/data-structures/graph/directed-graph.ts +146 -236
- package/src/data-structures/graph/map-graph.ts +63 -60
- package/src/data-structures/graph/undirected-graph.ts +129 -152
- package/src/data-structures/hash/hash-map.ts +274 -496
- package/src/data-structures/heap/heap.ts +389 -402
- package/src/data-structures/heap/max-heap.ts +12 -76
- package/src/data-structures/heap/min-heap.ts +13 -76
- package/src/data-structures/linked-list/doubly-linked-list.ts +426 -530
- package/src/data-structures/linked-list/singly-linked-list.ts +495 -517
- package/src/data-structures/linked-list/skip-linked-list.ts +1 -108
- package/src/data-structures/priority-queue/max-priority-queue.ts +12 -87
- package/src/data-structures/priority-queue/min-priority-queue.ts +11 -88
- package/src/data-structures/priority-queue/priority-queue.ts +3 -92
- package/src/data-structures/queue/deque.ts +381 -357
- package/src/data-structures/queue/queue.ts +310 -264
- package/src/data-structures/stack/stack.ts +217 -131
- package/src/data-structures/trie/trie.ts +240 -175
- package/src/interfaces/binary-tree.ts +240 -6
- package/src/interfaces/graph.ts +37 -0
- package/src/types/data-structures/base/base.ts +5 -5
- package/src/types/data-structures/graph/abstract-graph.ts +5 -0
- package/src/types/utils/utils.ts +2 -0
- package/src/utils/utils.ts +9 -14
|
@@ -5,7 +5,8 @@
|
|
|
5
5
|
* @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>
|
|
6
6
|
* @license MIT License
|
|
7
7
|
*/
|
|
8
|
-
|
|
8
|
+
|
|
9
|
+
import type { DijkstraResult, EntryCallback, GraphOptions, VertexKey } from '../../types';
|
|
9
10
|
import { uuidV4 } from '../../utils';
|
|
10
11
|
import { IterableEntryBase } from '../base';
|
|
11
12
|
import { IGraph } from '../../interfaces';
|
|
@@ -16,13 +17,6 @@ export abstract class AbstractVertex<V = any> {
|
|
|
16
17
|
key: VertexKey;
|
|
17
18
|
value: V | undefined;
|
|
18
19
|
|
|
19
|
-
/**
|
|
20
|
-
* The function is a protected constructor that takes an key and an optional value as parameters.
|
|
21
|
-
* @param {VertexKey} key - The `key` parameter is of type `VertexKey` and represents the identifier of the vertex. It is
|
|
22
|
-
* used to uniquely identify the vertex object.
|
|
23
|
-
* @param {V} [value] - The parameter "value" is an optional parameter of type V. It is used to assign a value to the
|
|
24
|
-
* vertex. If no value is provided, it will be set to undefined.
|
|
25
|
-
*/
|
|
26
20
|
protected constructor(key: VertexKey, value?: V) {
|
|
27
21
|
this.key = key;
|
|
28
22
|
this.value = value;
|
|
@@ -33,15 +27,6 @@ export abstract class AbstractEdge<E = any> {
|
|
|
33
27
|
value: E | undefined;
|
|
34
28
|
weight: number;
|
|
35
29
|
|
|
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
30
|
protected constructor(weight?: number, value?: E) {
|
|
46
31
|
this.weight = weight !== undefined ? weight : 1;
|
|
47
32
|
this.value = value;
|
|
@@ -53,13 +38,17 @@ export abstract class AbstractEdge<E = any> {
|
|
|
53
38
|
get hashCode(): string {
|
|
54
39
|
return this._hashCode;
|
|
55
40
|
}
|
|
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
41
|
}
|
|
62
42
|
|
|
43
|
+
/**
|
|
44
|
+
* Abstract graph over vertices and edges.
|
|
45
|
+
* @template V - Vertex value type.
|
|
46
|
+
* @template E - Edge value type.
|
|
47
|
+
* @template VO - Concrete vertex subclass (extends AbstractVertex<V>).
|
|
48
|
+
* @template EO - Concrete edge subclass (extends AbstractEdge<E>).
|
|
49
|
+
* @remarks Time O(1), Space O(1)
|
|
50
|
+
* @example examples will be generated by unit test
|
|
51
|
+
*/
|
|
63
52
|
export abstract class AbstractGraph<
|
|
64
53
|
V = any,
|
|
65
54
|
E = any,
|
|
@@ -69,8 +58,21 @@ export abstract class AbstractGraph<
|
|
|
69
58
|
extends IterableEntryBase<VertexKey, V | undefined>
|
|
70
59
|
implements IGraph<V, E, VO, EO>
|
|
71
60
|
{
|
|
72
|
-
|
|
61
|
+
/**
|
|
62
|
+
* Construct a graph with runtime defaults.
|
|
63
|
+
* @param options - `GraphOptions<V>` in `options.graph` (e.g. `vertexValueInitializer`, `defaultEdgeWeight`).
|
|
64
|
+
* @remarks Time O(1), Space O(1)
|
|
65
|
+
*/
|
|
66
|
+
constructor(options?: Partial<Record<string, unknown>>) {
|
|
73
67
|
super();
|
|
68
|
+
const graph = (options as any)?.graph as GraphOptions<V> | undefined;
|
|
69
|
+
this._options = { defaultEdgeWeight: 1, ...(graph ?? {}) };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
protected _options: GraphOptions<V> = { defaultEdgeWeight: 1 };
|
|
73
|
+
|
|
74
|
+
get options(): Readonly<GraphOptions<V>> {
|
|
75
|
+
return this._options;
|
|
74
76
|
}
|
|
75
77
|
|
|
76
78
|
protected _vertexMap: Map<VertexKey, VO> = new Map<VertexKey, VO>();
|
|
@@ -88,59 +90,96 @@ export abstract class AbstractGraph<
|
|
|
88
90
|
}
|
|
89
91
|
|
|
90
92
|
/**
|
|
91
|
-
*
|
|
92
|
-
*
|
|
93
|
-
* @param
|
|
94
|
-
* @
|
|
93
|
+
* Create a new vertex instance (implementation specific).
|
|
94
|
+
* @param key - Vertex identifier.
|
|
95
|
+
* @param value - Optional payload.
|
|
96
|
+
* @returns Concrete vertex instance.
|
|
97
|
+
* @remarks Time O(1), Space O(1)
|
|
95
98
|
*/
|
|
96
99
|
abstract createVertex(key: VertexKey, value?: V): VO;
|
|
97
100
|
|
|
98
101
|
/**
|
|
99
|
-
*
|
|
100
|
-
*
|
|
101
|
-
* @param
|
|
102
|
-
* @param
|
|
103
|
-
* @param
|
|
104
|
-
* @
|
|
102
|
+
* Create a new edge instance (implementation specific).
|
|
103
|
+
* @param srcOrV1 - Source/endpoint A key.
|
|
104
|
+
* @param destOrV2 - Destination/endpoint B key.
|
|
105
|
+
* @param weight - Edge weight (defaults may apply).
|
|
106
|
+
* @param value - Edge payload.
|
|
107
|
+
* @returns Concrete edge instance.
|
|
108
|
+
* @remarks Time O(1), Space O(1)
|
|
105
109
|
*/
|
|
106
110
|
abstract createEdge(srcOrV1: VertexKey, destOrV2: VertexKey, weight?: number, value?: E): EO;
|
|
107
111
|
|
|
112
|
+
/**
|
|
113
|
+
* Delete an edge by instance.
|
|
114
|
+
* @param edge - Edge instance.
|
|
115
|
+
* @returns Removed edge or `undefined`.
|
|
116
|
+
* @remarks Time O(1) avg, Space O(1)
|
|
117
|
+
*/
|
|
108
118
|
abstract deleteEdge(edge: EO): EO | undefined;
|
|
109
119
|
|
|
120
|
+
/**
|
|
121
|
+
* Get an edge between two vertices if present.
|
|
122
|
+
* @param srcOrKey - Source/endpoint A vertex or key.
|
|
123
|
+
* @param destOrKey - Destination/endpoint B vertex or key.
|
|
124
|
+
* @returns Edge instance or `undefined`.
|
|
125
|
+
* @remarks Time O(1) avg, Space O(1)
|
|
126
|
+
*/
|
|
110
127
|
abstract getEdge(srcOrKey: VO | VertexKey, destOrKey: VO | VertexKey): EO | undefined;
|
|
111
128
|
|
|
129
|
+
/**
|
|
130
|
+
* Degree of a vertex in this graph model.
|
|
131
|
+
* @param vertexOrKey - Vertex or key.
|
|
132
|
+
* @returns Non-negative integer degree.
|
|
133
|
+
* @remarks Time O(1) avg, Space O(1)
|
|
134
|
+
*/
|
|
112
135
|
abstract degreeOf(vertexOrKey: VO | VertexKey): number;
|
|
113
136
|
|
|
137
|
+
/**
|
|
138
|
+
* All edges in the graph (unique, order not guaranteed).
|
|
139
|
+
* @returns Array of edges.
|
|
140
|
+
* @remarks Time O(E), Space O(E)
|
|
141
|
+
*/
|
|
114
142
|
abstract edgeSet(): EO[];
|
|
115
143
|
|
|
144
|
+
/**
|
|
145
|
+
* Incident edges of a vertex.
|
|
146
|
+
* @param vertexOrKey - Vertex or key.
|
|
147
|
+
* @returns Array of incident edges.
|
|
148
|
+
* @remarks Time O(deg), Space O(deg)
|
|
149
|
+
*/
|
|
116
150
|
abstract edgesOf(vertexOrKey: VO | VertexKey): EO[];
|
|
117
151
|
|
|
152
|
+
/**
|
|
153
|
+
* One-step neighbors of a vertex.
|
|
154
|
+
* @param vertexOrKey - Vertex or key.
|
|
155
|
+
* @returns Array of neighbor vertices.
|
|
156
|
+
* @remarks Time O(deg), Space O(deg)
|
|
157
|
+
*/
|
|
118
158
|
abstract getNeighbors(vertexOrKey: VO | VertexKey): VO[];
|
|
119
159
|
|
|
160
|
+
/**
|
|
161
|
+
* Resolve endpoints of an edge to vertex instances.
|
|
162
|
+
* @param edge - Edge instance.
|
|
163
|
+
* @returns `[v1, v2]` or `undefined` if missing.
|
|
164
|
+
* @remarks Time O(1), Space O(1)
|
|
165
|
+
*/
|
|
120
166
|
abstract getEndsOfEdge(edge: EO): [VO, VO] | undefined;
|
|
121
167
|
|
|
122
168
|
/**
|
|
123
|
-
*
|
|
124
|
-
*
|
|
125
|
-
*
|
|
126
|
-
*
|
|
127
|
-
* @param {VertexKey} vertexKey - The `vertexKey` parameter is the identifier of the vertex that you want to retrieve from
|
|
128
|
-
* the `_vertexMap` map.
|
|
129
|
-
* @returns The method `getVertex` returns the vertex with the specified `vertexKey` if it exists in the `_vertexMap`
|
|
130
|
-
* map. If the vertex does not exist, it returns `undefined`.
|
|
169
|
+
* Get vertex instance by key.
|
|
170
|
+
* @param vertexKey - Vertex key.
|
|
171
|
+
* @returns Vertex instance or `undefined`.
|
|
172
|
+
* @remarks Time O(1), Space O(1)
|
|
131
173
|
*/
|
|
132
174
|
getVertex(vertexKey: VertexKey): VO | undefined {
|
|
133
175
|
return this._vertexMap.get(vertexKey) || undefined;
|
|
134
176
|
}
|
|
135
177
|
|
|
136
178
|
/**
|
|
137
|
-
*
|
|
138
|
-
*
|
|
139
|
-
*
|
|
140
|
-
*
|
|
141
|
-
* @param {VO | VertexKey} vertexOrKey - The parameter `vertexOrKey` can be either a vertex object (`VO`) or a vertex ID
|
|
142
|
-
* (`VertexKey`).
|
|
143
|
-
* @returns a boolean value.
|
|
179
|
+
* Whether a vertex exists.
|
|
180
|
+
* @param vertexOrKey - Vertex or key.
|
|
181
|
+
* @returns `true` if present, otherwise `false`.
|
|
182
|
+
* @remarks Time O(1) avg, Space O(1)
|
|
144
183
|
*/
|
|
145
184
|
hasVertex(vertexOrKey: VO | VertexKey): boolean {
|
|
146
185
|
return this._vertexMap.has(this._getVertexKey(vertexOrKey));
|
|
@@ -151,10 +190,12 @@ export abstract class AbstractGraph<
|
|
|
151
190
|
addVertex(key: VertexKey, value?: V): boolean;
|
|
152
191
|
|
|
153
192
|
/**
|
|
154
|
-
*
|
|
155
|
-
*
|
|
193
|
+
* Add a vertex by key/value or by pre-built vertex.
|
|
194
|
+
* @param keyOrVertex - Vertex key or existing vertex instance.
|
|
195
|
+
* @param value - Optional payload.
|
|
196
|
+
* @returns `true` if inserted; `false` when key already exists.
|
|
197
|
+
* @remarks Time O(1) avg, Space O(1)
|
|
156
198
|
*/
|
|
157
|
-
|
|
158
199
|
addVertex(keyOrVertex: VertexKey | VO, value?: V): boolean {
|
|
159
200
|
if (keyOrVertex instanceof AbstractVertex) {
|
|
160
201
|
return this._addVertex(keyOrVertex);
|
|
@@ -164,27 +205,30 @@ export abstract class AbstractGraph<
|
|
|
164
205
|
}
|
|
165
206
|
}
|
|
166
207
|
|
|
208
|
+
/**
|
|
209
|
+
* Type guard: check if a value is a valid vertex key.
|
|
210
|
+
* @param potentialKey - Value to test.
|
|
211
|
+
* @returns `true` if string/number; else `false`.
|
|
212
|
+
* @remarks Time O(1), Space O(1)
|
|
213
|
+
*/
|
|
167
214
|
isVertexKey(potentialKey: any): potentialKey is VertexKey {
|
|
168
215
|
const potentialKeyType = typeof potentialKey;
|
|
169
216
|
return potentialKeyType === 'string' || potentialKeyType === 'number';
|
|
170
217
|
}
|
|
171
218
|
|
|
172
219
|
/**
|
|
173
|
-
*
|
|
174
|
-
*
|
|
220
|
+
* Delete a vertex and its incident edges.
|
|
221
|
+
* @param vertexOrKey - Vertex or key.
|
|
222
|
+
* @returns `true` if removed; otherwise `false`.
|
|
223
|
+
* @remarks Time O(deg), Space O(1)
|
|
175
224
|
*/
|
|
176
|
-
|
|
177
225
|
abstract deleteVertex(vertexOrKey: VO | VertexKey): boolean;
|
|
178
226
|
|
|
179
227
|
/**
|
|
180
|
-
*
|
|
181
|
-
*
|
|
182
|
-
*
|
|
183
|
-
*
|
|
184
|
-
* @param {VO[] | VertexKey[]} vertexMap - The `vertexMap` parameter can be either an array of vertexMap (`VO[]`) or an array
|
|
185
|
-
* of vertex IDs (`VertexKey[]`).
|
|
186
|
-
* @returns a boolean value. It returns true if at least one vertex was successfully removed, and false if no vertexMap
|
|
187
|
-
* were removed.
|
|
228
|
+
* Delete multiple vertices.
|
|
229
|
+
* @param vertexMap - Array of vertices or keys.
|
|
230
|
+
* @returns `true` if any vertex was removed.
|
|
231
|
+
* @remarks Time O(sum(deg)), Space O(1)
|
|
188
232
|
*/
|
|
189
233
|
removeManyVertices(vertexMap: VO[] | VertexKey[]): boolean {
|
|
190
234
|
const removed: boolean[] = [];
|
|
@@ -195,15 +239,11 @@ export abstract class AbstractGraph<
|
|
|
195
239
|
}
|
|
196
240
|
|
|
197
241
|
/**
|
|
198
|
-
*
|
|
199
|
-
*
|
|
200
|
-
*
|
|
201
|
-
*
|
|
202
|
-
* @
|
|
203
|
-
* identifier of a vertex in a graph, while VO represents the type of the vertex object itself.
|
|
204
|
-
* @param {VertexKey | VO} v2 - The parameter `v2` represents the second vertex in the edge. It can be either a
|
|
205
|
-
* `VertexKey` or a `VO` type, which represents the type of the vertex.
|
|
206
|
-
* @returns A boolean value is being returned.
|
|
242
|
+
* Whether an edge exists between two vertices.
|
|
243
|
+
* @param v1 - Endpoint A vertex or key.
|
|
244
|
+
* @param v2 - Endpoint B vertex or key.
|
|
245
|
+
* @returns `true` if present; otherwise `false`.
|
|
246
|
+
* @remarks Time O(1) avg, Space O(1)
|
|
207
247
|
*/
|
|
208
248
|
hasEdge(v1: VertexKey | VO, v2: VertexKey | VO): boolean {
|
|
209
249
|
const edge = this.getEdge(v1, v2);
|
|
@@ -215,10 +255,14 @@ export abstract class AbstractGraph<
|
|
|
215
255
|
addEdge(src: VO | VertexKey, dest: VO | VertexKey, weight?: number, value?: E): boolean;
|
|
216
256
|
|
|
217
257
|
/**
|
|
218
|
-
*
|
|
219
|
-
*
|
|
258
|
+
* Add an edge by instance or by `(src, dest, weight?, value?)`.
|
|
259
|
+
* @param srcOrEdge - Edge instance or source vertex/key.
|
|
260
|
+
* @param dest - Destination vertex/key (when adding by pair).
|
|
261
|
+
* @param weight - Edge weight.
|
|
262
|
+
* @param value - Edge payload.
|
|
263
|
+
* @returns `true` if inserted; otherwise `false`.
|
|
264
|
+
* @remarks Time O(1) avg, Space O(1)
|
|
220
265
|
*/
|
|
221
|
-
|
|
222
266
|
addEdge(srcOrEdge: VO | VertexKey | EO, dest?: VO | VertexKey, weight?: number, value?: E): boolean {
|
|
223
267
|
if (srcOrEdge instanceof AbstractEdge) {
|
|
224
268
|
return this._addEdge(srcOrEdge);
|
|
@@ -236,18 +280,12 @@ export abstract class AbstractGraph<
|
|
|
236
280
|
}
|
|
237
281
|
|
|
238
282
|
/**
|
|
239
|
-
*
|
|
240
|
-
*
|
|
241
|
-
*
|
|
242
|
-
*
|
|
243
|
-
* @
|
|
244
|
-
*
|
|
245
|
-
* @param {VertexKey | VO} destOrKey - The `destOrKey` parameter represents the destination vertex of the edge. It can be
|
|
246
|
-
* either a `VertexKey` or a vertex object `VO`.
|
|
247
|
-
* @param {number} weight - The weight parameter represents the weight of the edge between the source vertex (srcOrKey)
|
|
248
|
-
* and the destination vertex (destOrKey).
|
|
249
|
-
* @returns a boolean value. If the edge exists between the source and destination vertexMap, the function will update
|
|
250
|
-
* the weight of the edge and return true. If the edge does not exist, the function will return false.
|
|
283
|
+
* Set the weight of an existing edge.
|
|
284
|
+
* @param srcOrKey - Source vertex or key.
|
|
285
|
+
* @param destOrKey - Destination vertex or key.
|
|
286
|
+
* @param weight - New weight.
|
|
287
|
+
* @returns `true` if updated; otherwise `false`.
|
|
288
|
+
* @remarks Time O(1) avg, Space O(1)
|
|
251
289
|
*/
|
|
252
290
|
setEdgeWeight(srcOrKey: VertexKey | VO, destOrKey: VertexKey | VO, weight: number): boolean {
|
|
253
291
|
const edge = this.getEdge(srcOrKey, destOrKey);
|
|
@@ -260,15 +298,12 @@ export abstract class AbstractGraph<
|
|
|
260
298
|
}
|
|
261
299
|
|
|
262
300
|
/**
|
|
263
|
-
*
|
|
264
|
-
*
|
|
265
|
-
*
|
|
266
|
-
*
|
|
267
|
-
* @
|
|
268
|
-
*
|
|
269
|
-
* @param {VO | VertexKey} v2 - The parameter `v2` represents either a vertex object (`VO`) or a vertex ID (`VertexKey`).
|
|
270
|
-
* @param limit - The count of limitation of result array.
|
|
271
|
-
* @returns The function `getAllPathsBetween` returns an array of arrays of vertexMap (`VO[][]`).
|
|
301
|
+
* Enumerate simple paths up to a limit.
|
|
302
|
+
* @param v1 - Source vertex or key.
|
|
303
|
+
* @param v2 - Destination vertex or key.
|
|
304
|
+
* @param limit - Maximum number of paths to collect.
|
|
305
|
+
* @returns Array of paths (each path is an array of vertices).
|
|
306
|
+
* @remarks Time O(paths) worst-case exponential, Space O(V + paths)
|
|
272
307
|
*/
|
|
273
308
|
getAllPathsBetween(v1: VO | VertexKey, v2: VO | VertexKey, limit = 1000): VO[][] {
|
|
274
309
|
const paths: VO[][] = [];
|
|
@@ -302,12 +337,10 @@ export abstract class AbstractGraph<
|
|
|
302
337
|
}
|
|
303
338
|
|
|
304
339
|
/**
|
|
305
|
-
*
|
|
306
|
-
*
|
|
307
|
-
*
|
|
308
|
-
*
|
|
309
|
-
* @param {VO[]} path - An array of vertexMap (VO) representing a path in a graph.
|
|
310
|
-
* @returns The function `getPathSumWeight` returns the sum of the weights of the edgeMap in the given path.
|
|
340
|
+
* Sum the weights along a vertex path.
|
|
341
|
+
* @param path - Sequence of vertices.
|
|
342
|
+
* @returns Path weight sum (0 if empty or edge missing).
|
|
343
|
+
* @remarks Time O(L), Space O(1) where L is path length
|
|
311
344
|
*/
|
|
312
345
|
getPathSumWeight(path: VO[]): number {
|
|
313
346
|
let sum = 0;
|
|
@@ -318,21 +351,12 @@ export abstract class AbstractGraph<
|
|
|
318
351
|
}
|
|
319
352
|
|
|
320
353
|
/**
|
|
321
|
-
*
|
|
322
|
-
*
|
|
323
|
-
*
|
|
324
|
-
*
|
|
325
|
-
*
|
|
326
|
-
* @
|
|
327
|
-
* @param {VO | VertexKey} v2 - The parameter `v2` represents the destination vertex or its ID. It is the vertex to which
|
|
328
|
-
* you want to find the minimum cost or weight from the source vertex `v1`.
|
|
329
|
-
* @param {boolean} [isWeight] - isWeight is an optional parameter that indicates whether the graph edgeMap have weights.
|
|
330
|
-
* If isWeight is set to true, the function will calculate the minimum cost between v1 and v2 based on the weights of
|
|
331
|
-
* the edgeMap. If isWeight is set to false or not provided, the function will calculate the
|
|
332
|
-
* @returns The function `getMinCostBetween` returns a number representing the minimum cost between two vertexMap (`v1`
|
|
333
|
-
* and `v2`). If the `isWeight` parameter is `true`, it calculates the minimum weight among all paths between the
|
|
334
|
-
* vertexMap. If `isWeight` is `false` or not provided, it uses a breadth-first search (BFS) algorithm to calculate the
|
|
335
|
-
* minimum number of
|
|
354
|
+
* Minimum hops/weight between two vertices.
|
|
355
|
+
* @param v1 - Source vertex or key.
|
|
356
|
+
* @param v2 - Destination vertex or key.
|
|
357
|
+
* @param isWeight - If `true`, compare by path weight; otherwise by hop count.
|
|
358
|
+
* @returns Minimum cost or `undefined` if missing/unreachable.
|
|
359
|
+
* @remarks Time O((V + E) log V) weighted / O(V + E) unweighted, Space O(V + E)
|
|
336
360
|
*/
|
|
337
361
|
getMinCostBetween(v1: VO | VertexKey, v2: VO | VertexKey, isWeight?: boolean): number | undefined {
|
|
338
362
|
if (isWeight === undefined) isWeight = false;
|
|
@@ -345,7 +369,6 @@ export abstract class AbstractGraph<
|
|
|
345
369
|
}
|
|
346
370
|
return min;
|
|
347
371
|
} else {
|
|
348
|
-
// BFS
|
|
349
372
|
const vertex2 = this._getVertex(v2);
|
|
350
373
|
const vertex1 = this._getVertex(v1);
|
|
351
374
|
if (!(vertex1 && vertex2)) {
|
|
@@ -357,12 +380,12 @@ export abstract class AbstractGraph<
|
|
|
357
380
|
visited.set(vertex1, true);
|
|
358
381
|
let cost = 0;
|
|
359
382
|
while (queue.length > 0) {
|
|
360
|
-
for (let i = 0
|
|
383
|
+
for (let i = 0, layerSize = queue.length; i < layerSize; i++) {
|
|
361
384
|
const cur = queue.shift();
|
|
362
385
|
if (cur === vertex2) {
|
|
363
386
|
return cost;
|
|
364
387
|
}
|
|
365
|
-
|
|
388
|
+
|
|
366
389
|
if (cur !== undefined) {
|
|
367
390
|
const neighbors = this.getNeighbors(cur);
|
|
368
391
|
for (const neighbor of neighbors) {
|
|
@@ -380,23 +403,13 @@ export abstract class AbstractGraph<
|
|
|
380
403
|
}
|
|
381
404
|
|
|
382
405
|
/**
|
|
383
|
-
*
|
|
384
|
-
*
|
|
385
|
-
*
|
|
386
|
-
*
|
|
387
|
-
*
|
|
388
|
-
* @
|
|
389
|
-
*
|
|
390
|
-
* @param {VO | VertexKey} v2 - VO | VertexKey - The second vertex or vertex ID between which we want to find the minimum
|
|
391
|
-
* path.
|
|
392
|
-
* @param {boolean} [isWeight] - A boolean flag indicating whether to consider the weight of edgeMap in finding the
|
|
393
|
-
* minimum path. If set to true, the function will use Dijkstra's algorithm to find the minimum weighted path. If set
|
|
394
|
-
* to false, the function will use breadth-first search (BFS) to find the minimum path.
|
|
395
|
-
* @param isDFS - If set to true, it enforces the use of getAllPathsBetween to first obtain all possible paths,
|
|
396
|
-
* followed by iterative computation of the shortest path. This approach may result in exponential time complexity,
|
|
397
|
-
* so the default method is to use the Dijkstra algorithm to obtain the shortest weighted path.
|
|
398
|
-
* @returns The function `getMinPathBetween` returns an array of vertexMap (`VO[]`) representing the minimum path between
|
|
399
|
-
* two vertexMap (`v1` and `v2`). If there is no path between the vertexMap, it returns `undefined`.
|
|
406
|
+
* Minimum path (as vertex sequence) between two vertices.
|
|
407
|
+
* @param v1 - Source vertex or key.
|
|
408
|
+
* @param v2 - Destination vertex or key.
|
|
409
|
+
* @param isWeight - If `true`, compare by path weight; otherwise by hop count.
|
|
410
|
+
* @param isDFS - For weighted mode only: if `true`, brute-force all paths; if `false`, use Dijkstra.
|
|
411
|
+
* @returns Vertex sequence, or `undefined`/empty when unreachable depending on branch.
|
|
412
|
+
* @remarks Time O((V + E) log V) weighted / O(V + E) unweighted, Space O(V + E)
|
|
400
413
|
*/
|
|
401
414
|
getMinPathBetween(v1: VO | VertexKey, v2: VO | VertexKey, isWeight?: boolean, isDFS = false): VO[] | undefined {
|
|
402
415
|
if (isWeight === undefined) isWeight = false;
|
|
@@ -417,10 +430,18 @@ export abstract class AbstractGraph<
|
|
|
417
430
|
}
|
|
418
431
|
return allPaths[minIndex] || undefined;
|
|
419
432
|
} else {
|
|
433
|
+
/**
|
|
434
|
+
* Dijkstra (binary-heap) shortest paths for non-negative weights.
|
|
435
|
+
* @param src - Source vertex or key.
|
|
436
|
+
* @param dest - Optional destination for early stop.
|
|
437
|
+
* @param getMinDist - If `true`, compute global minimum distance.
|
|
438
|
+
* @param genPaths - If `true`, also generate path arrays.
|
|
439
|
+
* @returns Result bag or `undefined` if source missing.
|
|
440
|
+
* @remarks Time O((V + E) log V), Space O(V + E)
|
|
441
|
+
*/
|
|
420
442
|
return this.dijkstra(v1, v2, true, true)?.minPath ?? [];
|
|
421
443
|
}
|
|
422
444
|
} else {
|
|
423
|
-
// DFS
|
|
424
445
|
let minPath: VO[] = [];
|
|
425
446
|
const vertex1 = this._getVertex(v1);
|
|
426
447
|
const vertex2 = this._getVertex(v2);
|
|
@@ -451,30 +472,20 @@ export abstract class AbstractGraph<
|
|
|
451
472
|
}
|
|
452
473
|
|
|
453
474
|
/**
|
|
454
|
-
*
|
|
455
|
-
*
|
|
456
|
-
*
|
|
457
|
-
*
|
|
458
|
-
*
|
|
459
|
-
* @
|
|
460
|
-
*
|
|
461
|
-
* @param {VO | VertexKey | undefined} [dest] - The `dest` parameter in the `dijkstraWithoutHeap` function is an optional
|
|
462
|
-
* parameter that specifies the destination vertex for the Dijkstra algorithm. It can be either a vertex object or its
|
|
463
|
-
* identifier. If no destination is provided, the value is set to `undefined`.
|
|
464
|
-
* @param {boolean} [getMinDist] - The `getMinDist` parameter is a boolean flag that determines whether the minimum
|
|
465
|
-
* distance from the source vertex to the destination vertex should be calculated and returned in the result. If
|
|
466
|
-
* `getMinDist` is set to `true`, the `minDist` property in the result will contain the minimum distance
|
|
467
|
-
* @param {boolean} [genPaths] - The `genPaths` parameter is a boolean flag that determines whether or not to generate
|
|
468
|
-
* paths in the Dijkstra algorithm. If `genPaths` is set to `true`, the algorithm will calculate and return the
|
|
469
|
-
* shortest paths from the source vertex to all other vertexMap in the graph. If `genPaths
|
|
470
|
-
* @returns The function `dijkstraWithoutHeap` returns an object of type `DijkstraResult<VO>`.
|
|
475
|
+
* Dijkstra without heap (array-based selection).
|
|
476
|
+
* @param src - Source vertex or key.
|
|
477
|
+
* @param dest - Optional destination for early stop.
|
|
478
|
+
* @param getMinDist - If `true`, compute global minimum distance.
|
|
479
|
+
* @param genPaths - If `true`, also generate path arrays.
|
|
480
|
+
* @returns Result bag or `undefined` if source missing.
|
|
481
|
+
* @remarks Time O(V^2 + E), Space O(V + E)
|
|
471
482
|
*/
|
|
472
483
|
dijkstraWithoutHeap(
|
|
473
484
|
src: VO | VertexKey,
|
|
474
485
|
dest: VO | VertexKey | undefined = undefined,
|
|
475
486
|
getMinDist: boolean = false,
|
|
476
487
|
genPaths: boolean = false
|
|
477
|
-
): DijkstraResult<VO> {
|
|
488
|
+
): DijkstraResult<VO> | undefined {
|
|
478
489
|
let minDist = Number.MAX_SAFE_INTEGER;
|
|
479
490
|
let minDest: VO | undefined = undefined;
|
|
480
491
|
let minPath: VO[] = [];
|
|
@@ -483,7 +494,7 @@ export abstract class AbstractGraph<
|
|
|
483
494
|
const vertexMap = this._vertexMap;
|
|
484
495
|
const distMap: Map<VO, number> = new Map();
|
|
485
496
|
const seen: Set<VO> = new Set();
|
|
486
|
-
const preMap: Map<VO, VO | undefined> = new Map();
|
|
497
|
+
const preMap: Map<VO, VO | undefined> = new Map();
|
|
487
498
|
const srcVertex = this._getVertex(src);
|
|
488
499
|
|
|
489
500
|
const destVertex = dest ? this._getVertex(dest) : undefined;
|
|
@@ -551,7 +562,7 @@ export abstract class AbstractGraph<
|
|
|
551
562
|
if (edge) {
|
|
552
563
|
const curFromMap = distMap.get(cur);
|
|
553
564
|
const neighborFromMap = distMap.get(neighbor);
|
|
554
|
-
|
|
565
|
+
|
|
555
566
|
if (curFromMap !== undefined && neighborFromMap !== undefined) {
|
|
556
567
|
if (edge.weight + curFromMap < neighborFromMap) {
|
|
557
568
|
distMap.set(neighbor, edge.weight + curFromMap);
|
|
@@ -579,32 +590,12 @@ export abstract class AbstractGraph<
|
|
|
579
590
|
return { distMap, preMap, seen, paths, minDist, minPath };
|
|
580
591
|
}
|
|
581
592
|
|
|
582
|
-
/**
|
|
583
|
-
* Time Complexity: O((V + E) * log(V)) - Depends on the implementation (using a binary heap).
|
|
584
|
-
* Space Complexity: O(V + E) - Depends on the implementation (using a binary heap).
|
|
585
|
-
*
|
|
586
|
-
* 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.
|
|
587
|
-
* The `dijkstra` function implements Dijkstra's algorithm to find the shortest path between a source vertex and an
|
|
588
|
-
* optional destination vertex, and optionally returns the minimum distance, the paths, and other information.
|
|
589
|
-
* @param {VO | VertexKey} src - The `src` parameter represents the source vertex from which the Dijkstra algorithm will
|
|
590
|
-
* start. It can be either a vertex object or a vertex ID.
|
|
591
|
-
* @param {VO | VertexKey | undefined} [dest] - The `dest` parameter is the destination vertex or vertex ID. It specifies the
|
|
592
|
-
* vertex to which the shortest path is calculated from the source vertex. If no destination is provided, the algorithm
|
|
593
|
-
* will calculate the shortest paths to all other vertexMap from the source vertex.
|
|
594
|
-
* @param {boolean} [getMinDist] - The `getMinDist` parameter is a boolean flag that determines whether the minimum
|
|
595
|
-
* distance from the source vertex to the destination vertex should be calculated and returned in the result. If
|
|
596
|
-
* `getMinDist` is set to `true`, the `minDist` property in the result will contain the minimum distance
|
|
597
|
-
* @param {boolean} [genPaths] - The `genPaths` parameter is a boolean flag that determines whether or not to generate
|
|
598
|
-
* paths in the Dijkstra algorithm. If `genPaths` is set to `true`, the algorithm will calculate and return the
|
|
599
|
-
* shortest paths from the source vertex to all other vertexMap in the graph. If `genPaths
|
|
600
|
-
* @returns The function `dijkstra` returns an object of type `DijkstraResult<VO>`.
|
|
601
|
-
*/
|
|
602
593
|
dijkstra(
|
|
603
594
|
src: VO | VertexKey,
|
|
604
595
|
dest: VO | VertexKey | undefined = undefined,
|
|
605
596
|
getMinDist: boolean = false,
|
|
606
597
|
genPaths: boolean = false
|
|
607
|
-
): DijkstraResult<VO> {
|
|
598
|
+
): DijkstraResult<VO> | undefined {
|
|
608
599
|
let minDist = Number.MAX_SAFE_INTEGER;
|
|
609
600
|
let minDest: VO | undefined = undefined;
|
|
610
601
|
let minPath: VO[] = [];
|
|
@@ -612,7 +603,7 @@ export abstract class AbstractGraph<
|
|
|
612
603
|
const vertexMap = this._vertexMap;
|
|
613
604
|
const distMap: Map<VO, number> = new Map();
|
|
614
605
|
const seen: Set<VO> = new Set();
|
|
615
|
-
const preMap: Map<VO, VO | undefined> = new Map();
|
|
606
|
+
const preMap: Map<VO, VO | undefined> = new Map();
|
|
616
607
|
|
|
617
608
|
const srcVertex = this._getVertex(src);
|
|
618
609
|
const destVertex = dest ? this._getVertex(dest) : undefined;
|
|
@@ -630,11 +621,6 @@ export abstract class AbstractGraph<
|
|
|
630
621
|
distMap.set(srcVertex, 0);
|
|
631
622
|
preMap.set(srcVertex, undefined);
|
|
632
623
|
|
|
633
|
-
/**
|
|
634
|
-
* The function `getPaths` retrieves all paths from vertexMap to a specified minimum vertex.
|
|
635
|
-
* @param {VO | undefined} minV - The parameter `minV` is of type `VO | undefined`. It represents the minimum vertex value or
|
|
636
|
-
* undefined.
|
|
637
|
-
*/
|
|
638
624
|
const getPaths = (minV: VO | undefined) => {
|
|
639
625
|
for (const vertex of vertexMap) {
|
|
640
626
|
const vertexOrKey = vertex[1];
|
|
@@ -674,7 +660,7 @@ export abstract class AbstractGraph<
|
|
|
674
660
|
const weight = this.getEdge(cur, neighbor)?.weight;
|
|
675
661
|
if (typeof weight === 'number') {
|
|
676
662
|
const distSrcToNeighbor = distMap.get(neighbor);
|
|
677
|
-
if (distSrcToNeighbor) {
|
|
663
|
+
if (distSrcToNeighbor !== undefined) {
|
|
678
664
|
if (dist + weight < distSrcToNeighbor) {
|
|
679
665
|
heap.add({ key: dist + weight, value: neighbor });
|
|
680
666
|
preMap.set(neighbor, cur);
|
|
@@ -707,22 +693,13 @@ export abstract class AbstractGraph<
|
|
|
707
693
|
}
|
|
708
694
|
|
|
709
695
|
/**
|
|
710
|
-
*
|
|
711
|
-
*
|
|
712
|
-
*
|
|
713
|
-
*
|
|
714
|
-
*
|
|
715
|
-
*
|
|
716
|
-
*
|
|
717
|
-
* @param {VO | VertexKey} src - The `src` parameter is the source vertex from which the Bellman-Ford algorithm will
|
|
718
|
-
* start calculating the shortest paths. It can be either a vertex object or a vertex ID.
|
|
719
|
-
* @param {boolean} [scanNegativeCycle] - A boolean flag indicating whether to scan for negative cycles in the graph.
|
|
720
|
-
* @param {boolean} [getMin] - The `getMin` parameter is a boolean flag that determines whether the algorithm should
|
|
721
|
-
* calculate the minimum distance from the source vertex to all other vertexMap in the graph. If `getMin` is set to
|
|
722
|
-
* `true`, the algorithm will find the minimum distance and update the `min` variable with the minimum
|
|
723
|
-
* @param {boolean} [genPath] - A boolean flag indicating whether to generate paths for all vertexMap from the source
|
|
724
|
-
* vertex.
|
|
725
|
-
* @returns The function `bellmanFord` returns an object with the following properties:
|
|
696
|
+
* Bellman-Ford single-source shortest paths with option to scan negative cycles.
|
|
697
|
+
* @param src - Source vertex or key.
|
|
698
|
+
* @param scanNegativeCycle - If `true`, also detect negative cycles.
|
|
699
|
+
* @param getMin - If `true`, compute global minimum distance.
|
|
700
|
+
* @param genPath - If `true`, generate path arrays via predecessor map.
|
|
701
|
+
* @returns Result bag including distances, predecessors, and optional cycle flag.
|
|
702
|
+
* @remarks Time O(V * E), Space O(V + E)
|
|
726
703
|
*/
|
|
727
704
|
bellmanFord(src: VO | VertexKey, scanNegativeCycle?: boolean, getMin?: boolean, genPath?: boolean) {
|
|
728
705
|
if (getMin === undefined) getMin = false;
|
|
@@ -731,10 +708,10 @@ export abstract class AbstractGraph<
|
|
|
731
708
|
const srcVertex = this._getVertex(src);
|
|
732
709
|
const paths: VO[][] = [];
|
|
733
710
|
const distMap: Map<VO, number> = new Map();
|
|
734
|
-
const preMap: Map<VO, VO> = new Map();
|
|
711
|
+
const preMap: Map<VO, VO> = new Map();
|
|
735
712
|
let min = Number.MAX_SAFE_INTEGER;
|
|
736
713
|
let minPath: VO[] = [];
|
|
737
|
-
|
|
714
|
+
|
|
738
715
|
let hasNegativeCycle: boolean | undefined;
|
|
739
716
|
if (scanNegativeCycle) hasNegativeCycle = false;
|
|
740
717
|
if (!srcVertex) return { hasNegativeCycle, distMap, preMap, paths, min, minPath };
|
|
@@ -813,34 +790,9 @@ export abstract class AbstractGraph<
|
|
|
813
790
|
}
|
|
814
791
|
|
|
815
792
|
/**
|
|
816
|
-
*
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
/**
|
|
820
|
-
* Dijkstra algorithm time: O(logVE) space: O(VO + EO)
|
|
821
|
-
* 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.
|
|
822
|
-
*/
|
|
823
|
-
|
|
824
|
-
/**
|
|
825
|
-
* BellmanFord time:O(VE) space:O(VO)
|
|
826
|
-
* one to rest pairs
|
|
827
|
-
* 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 edgeMap for several rounds to gradually approximate the shortest paths. Due to its ability to handle negative-weight edgeMap, the Bellman-Ford algorithm is more flexible in some scenarios.
|
|
828
|
-
* The `bellmanFord` function implements the Bellman-Ford algorithm to find the shortest path from a source vertex to
|
|
829
|
-
*/
|
|
830
|
-
|
|
831
|
-
/**
|
|
832
|
-
* Time Complexity: O(V^3) - Cubic time (Floyd-Warshall algorithm).
|
|
833
|
-
* Space Complexity: O(V^2) - Quadratic space (Floyd-Warshall algorithm).
|
|
834
|
-
*
|
|
835
|
-
* Not support graph with negative weight cycle
|
|
836
|
-
* all pairs
|
|
837
|
-
* 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 edgeMap, and it can simultaneously compute shortest paths between any two nodes.
|
|
838
|
-
* The function implements the Floyd-Warshall algorithm to find the shortest path between all pairs of vertexMap in a
|
|
839
|
-
* graph.
|
|
840
|
-
* @returns The function `floydWarshall()` returns an object with two properties: `costs` and `predecessor`. The `costs`
|
|
841
|
-
* property is a 2D array of numbers representing the shortest path costs between vertexMap in a graph. The
|
|
842
|
-
* `predecessor` property is a 2D array of vertexMap (or `undefined`) representing the predecessor vertexMap in the shortest
|
|
843
|
-
* path between vertexMap in the
|
|
793
|
+
* Floyd–Warshall all-pairs shortest paths.
|
|
794
|
+
* @returns `{ costs, predecessor }` matrices.
|
|
795
|
+
* @remarks Time O(V^3), Space O(V^2)
|
|
844
796
|
*/
|
|
845
797
|
floydWarshall(): { costs: number[][]; predecessor: (VO | undefined)[][] } {
|
|
846
798
|
const idAndVertices = [...this._vertexMap];
|
|
@@ -848,7 +800,6 @@ export abstract class AbstractGraph<
|
|
|
848
800
|
|
|
849
801
|
const costs: number[][] = [];
|
|
850
802
|
const predecessor: (VO | undefined)[][] = [];
|
|
851
|
-
// successors
|
|
852
803
|
|
|
853
804
|
for (let i = 0; i < n; i++) {
|
|
854
805
|
costs[i] = [];
|
|
@@ -878,8 +829,10 @@ export abstract class AbstractGraph<
|
|
|
878
829
|
}
|
|
879
830
|
|
|
880
831
|
/**
|
|
881
|
-
*
|
|
882
|
-
*
|
|
832
|
+
* Enumerate simple cycles (may be expensive).
|
|
833
|
+
* @param isInclude2Cycle - If `true`, include 2-cycles when graph semantics allow.
|
|
834
|
+
* @returns Array of cycles (each as array of vertex keys).
|
|
835
|
+
* @remarks Time exponential in worst-case, Space O(V + E)
|
|
883
836
|
*/
|
|
884
837
|
getCycles(isInclude2Cycle: boolean = false): VertexKey[][] {
|
|
885
838
|
const cycles: VertexKey[][] = [];
|
|
@@ -911,7 +864,6 @@ export abstract class AbstractGraph<
|
|
|
911
864
|
dfs(vertex, [], visited);
|
|
912
865
|
}
|
|
913
866
|
|
|
914
|
-
// Use a set to eliminate duplicate cycles
|
|
915
867
|
const uniqueCycles = new Map<string, VertexKey[]>();
|
|
916
868
|
|
|
917
869
|
for (const cycle of cycles) {
|
|
@@ -923,27 +875,25 @@ export abstract class AbstractGraph<
|
|
|
923
875
|
}
|
|
924
876
|
}
|
|
925
877
|
|
|
926
|
-
|
|
878
|
+
/**
|
|
879
|
+
* Map entries to an array via callback.
|
|
880
|
+
* @param callback - `(key, value, index, self) => T`.
|
|
881
|
+
* @param thisArg - Optional `this` for callback.
|
|
882
|
+
* @returns Mapped results.
|
|
883
|
+
* @remarks Time O(V), Space O(V)
|
|
884
|
+
*/
|
|
927
885
|
return [...uniqueCycles].map(cycleString => cycleString[1]);
|
|
928
886
|
}
|
|
929
887
|
|
|
930
888
|
/**
|
|
931
|
-
*
|
|
932
|
-
*
|
|
933
|
-
*
|
|
934
|
-
*
|
|
935
|
-
*
|
|
936
|
-
* @
|
|
937
|
-
* `value`, `key`, `index`, and `this`. It is used to determine whether an element should be included
|
|
938
|
-
* in the filtered array. The callback function should return `true` if the element should be
|
|
939
|
-
* included, and `
|
|
940
|
-
* @param {any} [thisArg] - The `thisArg` parameter is an optional argument that allows you to
|
|
941
|
-
* specify the value of `this` within the `predicate` function. It is used when you want to bind a
|
|
942
|
-
* specific object as the context for the `predicate` function. If `thisArg` is provided, it will be
|
|
943
|
-
* @returns The `filter` method returns an array of key-value pairs `[VertexKey, V | undefined][]`
|
|
944
|
-
* that satisfy the given predicate function.
|
|
889
|
+
* Induced-subgraph filter: keep vertices where `predicate(key, value)` is true,
|
|
890
|
+
* and only keep edges whose endpoints both survive.
|
|
891
|
+
* @param predicate - `(key, value, index, self) => boolean`.
|
|
892
|
+
* @param thisArg - Optional `this` for callback.
|
|
893
|
+
* @returns A new graph of the same concrete class (`this` type).
|
|
894
|
+
* @remarks Time O(V + E), Space O(V + E)
|
|
945
895
|
*/
|
|
946
|
-
filter(predicate: EntryCallback<VertexKey, V | undefined, boolean>, thisArg?: any):
|
|
896
|
+
filter(predicate: EntryCallback<VertexKey, V | undefined, boolean>, thisArg?: any): this {
|
|
947
897
|
const filtered: [VertexKey, V | undefined][] = [];
|
|
948
898
|
let index = 0;
|
|
949
899
|
for (const [key, value] of this) {
|
|
@@ -952,22 +902,28 @@ export abstract class AbstractGraph<
|
|
|
952
902
|
}
|
|
953
903
|
index++;
|
|
954
904
|
}
|
|
955
|
-
return filtered;
|
|
905
|
+
return this._createLike(filtered, this._snapshotOptions());
|
|
956
906
|
}
|
|
957
907
|
|
|
958
908
|
/**
|
|
959
|
-
*
|
|
960
|
-
*
|
|
961
|
-
*
|
|
962
|
-
* The `map` function iterates over the elements of a collection and applies a callback function to
|
|
963
|
-
* each element, returning an array of the results.
|
|
964
|
-
* @param callback - The callback parameter is a function that will be called for each element in the
|
|
965
|
-
* map. It takes four arguments:
|
|
966
|
-
* @param {any} [thisArg] - The `thisArg` parameter is an optional argument that allows you to
|
|
967
|
-
* specify the value of `this` within the callback function. If `thisArg` is provided, it will be
|
|
968
|
-
* used as the `this` value when calling the callback function. If `thisArg` is not provided, `
|
|
969
|
-
* @returns The `map` function is returning an array of type `T[]`.
|
|
909
|
+
* Preserve the old behavior: return filtered entries as an array.
|
|
910
|
+
* @remarks Time O(V), Space O(V)
|
|
970
911
|
*/
|
|
912
|
+
filterEntries(
|
|
913
|
+
predicate: EntryCallback<VertexKey, V | undefined, boolean>,
|
|
914
|
+
thisArg?: any
|
|
915
|
+
): [VertexKey, V | undefined][] {
|
|
916
|
+
const filtered: [VertexKey, V | undefined][] = [];
|
|
917
|
+
let index = 0;
|
|
918
|
+
for (const [key, value] of this) {
|
|
919
|
+
if (predicate.call(thisArg, key, value, index, this)) {
|
|
920
|
+
filtered.push([key, value]);
|
|
921
|
+
}
|
|
922
|
+
index++;
|
|
923
|
+
}
|
|
924
|
+
return filtered;
|
|
925
|
+
}
|
|
926
|
+
|
|
971
927
|
map<T>(callback: EntryCallback<VertexKey, V | undefined, T>, thisArg?: any): T[] {
|
|
972
928
|
const mapped: T[] = [];
|
|
973
929
|
let index = 0;
|
|
@@ -978,28 +934,147 @@ export abstract class AbstractGraph<
|
|
|
978
934
|
return mapped;
|
|
979
935
|
}
|
|
980
936
|
|
|
937
|
+
/**
|
|
938
|
+
* Create a deep clone of the graph with the same species.
|
|
939
|
+
* @remarks Time O(V + E), Space O(V + E)
|
|
940
|
+
*/
|
|
941
|
+
/**
|
|
942
|
+
* Create a deep clone of the graph with the same species.
|
|
943
|
+
* @returns A new graph of the same concrete class (`this` type).
|
|
944
|
+
* @remarks Time O(V + E), Space O(V + E)
|
|
945
|
+
*/
|
|
946
|
+
clone(): this {
|
|
947
|
+
return this._createLike(undefined, this._snapshotOptions());
|
|
948
|
+
}
|
|
949
|
+
|
|
950
|
+
// ===== Same-species factory & cloning helpers =====
|
|
951
|
+
|
|
952
|
+
/**
|
|
953
|
+
* Internal iterator over `[key, value]` entries in insertion order.
|
|
954
|
+
* @returns Iterator of `[VertexKey, V | undefined]`.
|
|
955
|
+
* @remarks Time O(V), Space O(1)
|
|
956
|
+
*/
|
|
981
957
|
protected *_getIterator(): IterableIterator<[VertexKey, V | undefined]> {
|
|
982
958
|
for (const vertex of this._vertexMap.values()) {
|
|
983
959
|
yield [vertex.key, vertex.value];
|
|
984
960
|
}
|
|
985
961
|
}
|
|
986
962
|
|
|
963
|
+
/**
|
|
964
|
+
* Capture configuration needed to reproduce the current graph.
|
|
965
|
+
* Currently the graph has no runtime options, so we return an empty object.
|
|
966
|
+
*/
|
|
967
|
+
/**
|
|
968
|
+
* Capture configuration needed to reproduce the current graph.
|
|
969
|
+
* @returns Options bag (opaque to callers).
|
|
970
|
+
* @remarks Time O(1), Space O(1)
|
|
971
|
+
*/
|
|
972
|
+
protected _snapshotOptions(): Record<string, unknown> {
|
|
973
|
+
return { graph: { ...this._options } };
|
|
974
|
+
}
|
|
975
|
+
|
|
976
|
+
/**
|
|
977
|
+
* Create an empty graph instance of the same concrete species (Directed/Undirected/etc).
|
|
978
|
+
* @remarks Time O(1), Space O(1)
|
|
979
|
+
*/
|
|
980
|
+
/**
|
|
981
|
+
* Create an empty graph instance of the same concrete species.
|
|
982
|
+
* @param _options - Snapshot options from `_snapshotOptions()`.
|
|
983
|
+
* @returns A new empty graph instance of `this` type.
|
|
984
|
+
* @remarks Time O(1), Space O(1)
|
|
985
|
+
*/
|
|
986
|
+
protected _createInstance(_options?: Partial<Record<string, unknown>>): this {
|
|
987
|
+
const Ctor: any = (this as any).constructor;
|
|
988
|
+
const instance: this = new Ctor();
|
|
989
|
+
const graph = (_options as any)?.graph as GraphOptions<V> | undefined;
|
|
990
|
+
if (graph) (instance as any)._options = { ...(instance as any)._options, ...graph };
|
|
991
|
+
else (instance as any)._options = { ...(instance as any)._options, ...(this as any)._options };
|
|
992
|
+
return instance;
|
|
993
|
+
}
|
|
994
|
+
|
|
995
|
+
/**
|
|
996
|
+
* Create a same-species graph populated with the given entries.
|
|
997
|
+
* Also preserves edges between kept vertices from the source graph.
|
|
998
|
+
* @remarks Time O(V + E), Space O(V + E)
|
|
999
|
+
*/
|
|
1000
|
+
/**
|
|
1001
|
+
* Create a same-species graph populated with entries; preserves edges among kept vertices.
|
|
1002
|
+
* @param iter - Optional entries to seed the new graph.
|
|
1003
|
+
* @param options - Snapshot options.
|
|
1004
|
+
* @returns A new graph of `this` type.
|
|
1005
|
+
* @remarks Time O(V + E), Space O(V + E)
|
|
1006
|
+
*/
|
|
1007
|
+
protected _createLike(iter?: Iterable<[VertexKey, V | undefined]>, options?: Partial<Record<string, unknown>>): this {
|
|
1008
|
+
const g = this._createInstance(options);
|
|
1009
|
+
// 1) Add vertices
|
|
1010
|
+
if (iter) {
|
|
1011
|
+
for (const [k, v] of iter) {
|
|
1012
|
+
(g as any).addVertex(k as VertexKey, v as V | undefined);
|
|
1013
|
+
}
|
|
1014
|
+
} else {
|
|
1015
|
+
for (const [k, v] of this) {
|
|
1016
|
+
(g as any).addVertex(k as VertexKey, v as V | undefined);
|
|
1017
|
+
}
|
|
1018
|
+
}
|
|
1019
|
+
// 2) Add edges whose endpoints exist in the new graph
|
|
1020
|
+
const edges = this.edgeSet();
|
|
1021
|
+
for (const e of edges as any[]) {
|
|
1022
|
+
const ends = this.getEndsOfEdge(e as any) as unknown as [any, any] | undefined;
|
|
1023
|
+
if (!ends) continue;
|
|
1024
|
+
const [va, vb] = ends;
|
|
1025
|
+
const ka = (va as any).key as VertexKey;
|
|
1026
|
+
const kb = (vb as any).key as VertexKey;
|
|
1027
|
+
const hasA = (g as any).hasVertex ? (g as any).hasVertex(ka) : false;
|
|
1028
|
+
const hasB = (g as any).hasVertex ? (g as any).hasVertex(kb) : false;
|
|
1029
|
+
if (hasA && hasB) {
|
|
1030
|
+
const w = (e as any).weight;
|
|
1031
|
+
const val = (e as any).value;
|
|
1032
|
+
const newEdge = (g as any).createEdge(ka, kb, w, val);
|
|
1033
|
+
(g as any)._addEdge(newEdge);
|
|
1034
|
+
}
|
|
1035
|
+
}
|
|
1036
|
+
return g;
|
|
1037
|
+
}
|
|
1038
|
+
|
|
1039
|
+
/**
|
|
1040
|
+
* Internal hook to attach an edge into adjacency structures.
|
|
1041
|
+
* @param edge - Edge instance.
|
|
1042
|
+
* @returns `true` if inserted; otherwise `false`.
|
|
1043
|
+
* @remarks Time O(1) avg, Space O(1)
|
|
1044
|
+
*/
|
|
987
1045
|
protected abstract _addEdge(edge: EO): boolean;
|
|
988
1046
|
|
|
1047
|
+
/**
|
|
1048
|
+
* Insert a pre-built vertex into the graph.
|
|
1049
|
+
* @param newVertex - Concrete vertex instance.
|
|
1050
|
+
* @returns `true` if inserted; `false` if key already exists.
|
|
1051
|
+
* @remarks Time O(1) avg, Space O(1)
|
|
1052
|
+
*/
|
|
989
1053
|
protected _addVertex(newVertex: VO): boolean {
|
|
990
1054
|
if (this.hasVertex(newVertex)) {
|
|
991
1055
|
return false;
|
|
992
|
-
// throw (new Error('Duplicated vertex key is not allowed'));
|
|
993
1056
|
}
|
|
994
1057
|
this._vertexMap.set(newVertex.key, newVertex);
|
|
995
1058
|
return true;
|
|
996
1059
|
}
|
|
997
1060
|
|
|
1061
|
+
/**
|
|
1062
|
+
* Resolve a vertex key or instance to the concrete vertex instance.
|
|
1063
|
+
* @param vertexOrKey - Vertex key or existing vertex.
|
|
1064
|
+
* @returns Vertex instance or `undefined`.
|
|
1065
|
+
* @remarks Time O(1), Space O(1)
|
|
1066
|
+
*/
|
|
998
1067
|
protected _getVertex(vertexOrKey: VertexKey | VO): VO | undefined {
|
|
999
1068
|
const vertexKey = this._getVertexKey(vertexOrKey);
|
|
1000
1069
|
return this._vertexMap.get(vertexKey) || undefined;
|
|
1001
1070
|
}
|
|
1002
1071
|
|
|
1072
|
+
/**
|
|
1073
|
+
* Resolve a vertex key from a key or vertex instance.
|
|
1074
|
+
* @param vertexOrKey - Vertex key or existing vertex.
|
|
1075
|
+
* @returns The vertex key.
|
|
1076
|
+
* @remarks Time O(1), Space O(1)
|
|
1077
|
+
*/
|
|
1003
1078
|
protected _getVertexKey(vertexOrKey: VO | VertexKey): VertexKey {
|
|
1004
1079
|
return vertexOrKey instanceof AbstractVertex ? vertexOrKey.key : vertexOrKey;
|
|
1005
1080
|
}
|