detectCycles method
Detects cycles in the graph using depth-first search.
A cycle exists when you can follow connections from a node and eventually return to the same node.
Returns a list of cycles, where each cycle is represented as a list of node IDs forming the cycle. Returns an empty list if no cycles are found.
Example:
final cycles = controller.detectCycles();
if (cycles.isNotEmpty) {
print('Found ${cycles.length} cycles in the graph');
for (final cycle in cycles) {
print('Cycle: ${cycle.join(' -> ')}');
}
}
Implementation
List<List<String>> detectCycles() {
// Simple cycle detection implementation
final cycles = <List<String>>[];
final visited = <String>{};
final recursionStack = <String>{};
void dfs(String nodeId, List<String> path) {
if (recursionStack.contains(nodeId)) {
// Found a cycle
final cycleStart = path.indexOf(nodeId);
if (cycleStart >= 0) {
cycles.add(path.sublist(cycleStart));
}
return;
}
if (visited.contains(nodeId)) return;
visited.add(nodeId);
recursionStack.add(nodeId);
path.add(nodeId);
// Follow outgoing connections
final outgoingConnections = _connections.where(
(c) => c.sourceNodeId == nodeId,
);
for (final conn in outgoingConnections) {
dfs(conn.targetNodeId, List.from(path));
}
recursionStack.remove(nodeId);
path.removeLast();
}
for (final node in _nodes.values) {
if (!visited.contains(node.id)) {
dfs(node.id, []);
}
}
return cycles;
}