floydWarshallSearch<V> function

FloydWarshall<V> floydWarshallSearch<V>({
  1. required Iterable<V> vertices,
  2. required Iterable<V> successorsOf(
    1. V vertex
    ),
  3. num edgeCost(
    1. V source,
    2. V target
    )?,
  4. StorageStrategy<V>? vertexStrategy,
})

Floyd-Warshall all-pairs shortest paths algorithm.

Computes all shortest paths between all pairs of vertices in a graph.

See https://en.wikipedia.org/wiki/Floyd%E2%80%93Warshall_algorithm.

Implementation

FloydWarshall<V> floydWarshallSearch<V>({
  required Iterable<V> vertices,
  required Iterable<V> Function(V vertex) successorsOf,
  num Function(V source, V target)? edgeCost,
  StorageStrategy<V>? vertexStrategy,
}) {
  edgeCost = edgeCost ?? constantFunction2(1);
  vertexStrategy = vertexStrategy ?? StorageStrategy.defaultStrategy();

  // Step 1: Initialize matrix states.
  final pairs = vertexStrategy.createMap<Map<V, FloydWarshallState<V>>>();
  for (final source in vertices) {
    final sourceMap = vertexStrategy.createMap<FloydWarshallState<V>>();
    for (final target in vertices) {
      sourceMap[target] = FloydWarshallState<V>(
        distance: source == target ? 0 : double.infinity,
      );
    }
    for (final target in successorsOf(source)) {
      final state = sourceMap[target];
      if (state != null) {
        final cost = edgeCost(source, target);
        if (source == target) {
          if (cost < state.distance) {
            state.distance = cost;
            state.next = target;
          }
        } else if (state.next == null || cost < state.distance) {
          state.distance = cost;
          state.next = target;
        }
      }
    }
    pairs[source] = sourceMap;
  }

  // Step 2: Floyd-Warshall loops.
  for (final k in vertices) {
    final rowK = pairs[k]!;
    for (final i in vertices) {
      final rowI = pairs[i]!;
      final ik = rowI[k]!;
      if (ik.distance.isInfinite) continue;
      for (final j in vertices) {
        final kj = rowK[j]!;
        if (kj.distance.isInfinite) continue;
        final ij = rowI[j]!;
        final distance = ik.distance + kj.distance;
        if (distance < ij.distance) {
          ij.distance = distance;
          ij.next = ik.next;
        }
      }
    }
  }

  // Step 3: Check for negative cycles.
  for (final vertex in vertices) {
    if (pairs[vertex]![vertex]!.distance < 0) {
      throw GraphError(
        vertex,
        'vertex',
        'Graph contains a negative-weight cycle',
      );
    }
  }

  return FloydWarshall(edgeCost, pairs);
}