Chapters

Hide chapters

Data Structures & Algorithms in Dart

Second Edition · Flutter · Dart 3.0 · VS Code 1.78

Section VI: Challenge Solutions

Section 6: 21 chapters
Show chapters Hide chapters

24. Chapter 24 Solutions
Written by Jonathan Sande

Heads up... You're reading this book for free, with parts of this chapter shown beyond this point as scrambled text.

Solution to Challenge 1

These are the shortest paths from A to the following vertices:

  • Path to B: A - (1) - B
  • Path to C: A - (1) - B - (8) - C
  • Path to D: A - (1) - B - (9) - D
  • Path to E: A - (1) - B - (8) - C - (2) - E

Solution to Challenge 2

To get the shortest paths from the source vertex to every other vertex in the graph, use the following extension on Dijkstra:

extension ShortestPaths<E> on Dijkstra<E> {
  Map<Vertex<E>, List<Vertex<E>>> shortestPathsLists(
    Vertex<E> source,
  ) {
    // 1
    final allPathsLists = <Vertex<E>, List<Vertex<E>>>{};
    // 2
    final allPaths = shortestPaths(source);
    // 3
    for (final vertex in graph.vertices) {
      final path = shortestPath(
        source,
        vertex,
        paths: allPaths,
      );
      allPathsLists[vertex] = path;
    }
    return allPathsLists;
  }
}
Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.

You're reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a Kodeco Personal Plan.

Unlock now