undirected-graph.ts 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. /**
  2. * Copyright (c) 2021 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author David Sehnal <david.sehnal@gmail.com>
  5. */
  6. import { arraySetAdd } from '../../mol-util/array';
  7. export { UndirectedGraph };
  8. class UndirectedGraph<T extends string | number, S = T> {
  9. vertices = new Map<T, S | undefined>();
  10. edges = new Map<T, T[]>();
  11. addVertex(a: T, s?: S) {
  12. this.vertices.set(a, s);
  13. if (!this.edges.has(a)) {
  14. this.edges.set(a, []);
  15. }
  16. }
  17. addEdge(a: T, b: T) {
  18. arraySetAdd(this.edges.get(a)!, b);
  19. arraySetAdd(this.edges.get(b)!, a);
  20. }
  21. /**
  22. * Returns a connected component induced by a and
  23. * its unique representative.
  24. */
  25. getComponent(a: T) {
  26. let pivot = a;
  27. const component: T[] = [];
  28. const visited = new Set<T>();
  29. const stack = [a];
  30. while (stack.length > 0) {
  31. const e = stack.pop()!;
  32. component.push(e);
  33. visited.add(e);
  34. if (e < pivot) pivot = e;
  35. for (const b of this.edges.get(e)!) {
  36. if (visited.has(b)) continue;
  37. stack.push(b);
  38. }
  39. }
  40. return { pivot, component };
  41. }
  42. }