Graph.fromAdjacencyListString constructor

Graph.fromAdjacencyListString(
  1. String adjacencyListString
)

Create a Graph using a String format of its adjacency list.

The accepted format is similar to the NetworkX adjacency list format. Here, comments or any other arbitrary data is not allowed and will result in a FormatException.

Implementation

factory Graph.fromAdjacencyListString(String adjacencyListString) {
  final AdjacencyList adjacencyList = {};

  for (final line in adjacencyListString.split(RegExp(r'\r?\n'))) {
    final nodes = line.split(' ');

    // Allowing only one (source) node in an adjacency list line may be
    // convenient in some cases.
    if (nodes.isEmpty) {
      throw FormatException(
          'An adjacency list cannot contain an empty line.', line);
    }

    final sourceNode = IntegerNode(int.parse(nodes.first));
    final targetNodes = nodes
        .skip(1)
        .map((stringId) => IntegerNode(int.parse(stringId)))
        .toSet();
    adjacencyList[sourceNode] = targetNodes;
  }

  return Graph.fromAdjacencyList(adjacencyList);
}