All files / src/data-structures/graph abstract-graph.ts

67.32% Statements 307/456
58.94% Branches 112/190
65.38% Functions 34/52
68.2% Lines 281/412

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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