vis.js is a dynamic, browser-based visualization library
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

67 lines
2.0 KiB

  1. /**
  2. * The FloydWarshall algorithm is an algorithm for finding shortest paths in
  3. * a weighted graph with positive or negative edge weights (but with no negative
  4. * cycles). - https://en.wikipedia.org/wiki/Floyd–Warshall_algorithm
  5. */
  6. class FloydWarshall {
  7. /**
  8. * @ignore
  9. */
  10. constructor() {
  11. }
  12. /**
  13. *
  14. * @param {Object} body
  15. * @param {Array.<Node>} nodesArray
  16. * @param {Array.<Edge>} edgesArray
  17. * @returns {{}}
  18. */
  19. getDistances(body, nodesArray, edgesArray) {
  20. let D_matrix = {};
  21. let edges = body.edges;
  22. // prepare matrix with large numbers
  23. for (let i = 0; i < nodesArray.length; i++) {
  24. let node = nodesArray[i];
  25. let cell = {};
  26. D_matrix[node] = cell;
  27. for (let j = 0; j < nodesArray.length; j++) {
  28. cell[nodesArray[j]] = (i == j ? 0 : 1e9);
  29. }
  30. }
  31. // put the weights for the edges in. This assumes unidirectionality.
  32. for (let i = 0; i < edgesArray.length; i++) {
  33. let edge = edges[edgesArray[i]];
  34. // edge has to be connected if it counts to the distances. If it is connected to inner clusters it will crash so we also check if it is in the D_matrix
  35. if (edge.connected === true && D_matrix[edge.fromId] !== undefined && D_matrix[edge.toId] !== undefined) {
  36. D_matrix[edge.fromId][edge.toId] = 1;
  37. D_matrix[edge.toId][edge.fromId] = 1;
  38. }
  39. }
  40. let nodeCount = nodesArray.length;
  41. // Adapted FloydWarshall based on unidirectionality to greatly reduce complexity.
  42. for (let k = 0; k < nodeCount; k++) {
  43. let knode = nodesArray[k];
  44. let kcolm = D_matrix[knode];
  45. for (let i = 0; i < nodeCount - 1; i++) {
  46. let inode = nodesArray[i];
  47. let icolm = D_matrix[inode];
  48. for (let j = i + 1; j < nodeCount; j++) {
  49. let jnode = nodesArray[j];
  50. let jcolm = D_matrix[jnode];
  51. let val = Math.min(icolm[jnode], icolm[knode] + kcolm[jnode]);
  52. icolm[jnode] = val;
  53. jcolm[inode] = val;
  54. }
  55. }
  56. }
  57. return D_matrix;
  58. }
  59. }
  60. export default FloydWarshall;