mappedTree method

Map<T, List<Set<T>>> mappedTree(
  1. T start, [
  2. T? target
])

Returns a map containing all paths commencing at start.

  • Each entry of type Set<T> represents a path (the start vertex is omitted).
  • Paths are grouped according to the last vertex in the path list.
  • If a target vertex is specified the function will return after a path from start to target was found and added to the map.
  • Inspired by graphs.

Usage:

import 'package:directed_graph/directed_graph.dart';
void main() {
  var graph = DirectedGraph<String, int>(
    {
      'a': {'a', 'b', 'h', 'c', 'e'},
      'b': {'h'},
      'c': {'h', 'g'},
      'd': {'e', 'f'},
      'e': {'g'},
      'f': {'i'},
      'i': {'l', 'k'},
      'k': {'g', 'f'},
     }
  );
  final crawler = GraphCrawler<String>(graph.edges);
  final treeMap = crawler.mappedTree('a', 'g');
  print(treeMap);
}

The program above generates the following console output:

{a: [{a}], b: [{b}], h: [{h}, {b, h}, {c, h}], c: [{c}], e: [{e}], g: [{c, g}]}

Implementation

Map<T, List<Set<T>>> mappedTree(T start, [T? target]) {
  final result = <T, List<Set<T>>>{};
  final tree = this.tree(start, target);
  for (final branch in tree) {
    if (result.containsKey(branch.last)) {
      result[branch.last]!.add(branch);
    } else {
      result[branch.last] = [branch];
    }
  }
  return result;
}