hasCycleUndirected<T> function

bool hasCycleUndirected<T>(
  1. Map<T, List<T>> graph
)

Implementation

bool hasCycleUndirected<T>(Map<T, List<T>> graph) {
  final Set<T> visited = <T>{};

  bool dfs(T node, T? parent) {
    visited.add(node);
    for (final T neighbor in graph[node] ?? const []) {
      if (!visited.contains(neighbor)) {
        if (dfs(neighbor, node)) return true;
      } else if (neighbor != parent) {
        return true;
      }
    }
    return false;
  }

  final Set<T> nodes = {...graph.keys};
  for (final neighbors in graph.values) {
    nodes.addAll(neighbors);
  }
  for (final T node in nodes) {
    if (!visited.contains(node)) {
      if (dfs(node, null)) return true;
    }
  }
  return false;
}