using System; using System.Collections.Generic; using System.Linq; namespace MoonTools.Core.Graph { public enum SearchSymbol { start, finish } public class DirectedGraph : IGraph { protected HashSet nodes = new HashSet(); protected HashSet<(TNode, TNode)> edges = new HashSet<(TNode, TNode)>(); protected Dictionary<(TNode, TNode), TEdgeData> edgesToEdgeData = new Dictionary<(TNode, TNode), TEdgeData>(); protected Dictionary> neighbors = new Dictionary>(); private class SimpleCycleComparer : IEqualityComparer> { public bool Equals(IEnumerable x, IEnumerable y) { return x.SequenceEqual(y); } public int GetHashCode(IEnumerable obj) { return obj.Aggregate(0, (current, next) => current.GetHashCode() ^ next.GetHashCode()); } } public IEnumerable Nodes { get { return nodes; } } public IEnumerable<(TNode, TNode)> Edges { get { return edges; } } public bool Exists(TNode node) { return nodes.Contains(node); } public bool Exists((TNode, TNode) edge) { return edges.Contains(edge); } public void AddNode(TNode node) { if (!Exists(node)) { nodes.Add(node); neighbors.Add(node, new HashSet()); } } public void AddNodes(params TNode[] nodes) { foreach (var node in nodes) { AddNode(node); } } public void RemoveNode(TNode node) { var edgesToRemove = new List<(TNode, TNode)>(); if (Exists(node)) { foreach (var entry in neighbors) { if (entry.Value.Contains(node)) { edgesToRemove.Add((entry.Key, node)); } } foreach (var edge in edgesToRemove) { RemoveEdge(edge.Item1, edge.Item2); } nodes.Remove(node); neighbors.Remove(node); } } public void AddEdge(TNode v, TNode u, TEdgeData edgeData) { if (Exists(v) && Exists(u)) { neighbors[v].Add(u); edges.Add((v, u)); this.edgesToEdgeData.Add((v, u), edgeData); } } public void AddEdges(params (TNode, TNode, TEdgeData)[] edges) { foreach (var edge in edges) { AddEdge(edge.Item1, edge.Item2, edge.Item3); } } public void RemoveEdge(TNode v, TNode u) { neighbors[v].Remove(u); } public TEdgeData EdgeData((TNode, TNode) edge) { return edgesToEdgeData[edge]; } public IEnumerable Neighbors(TNode node) { if (Exists(node)) { return neighbors[node]; } else { return Enumerable.Empty(); } } public Dictionary> NodeDFS() { var discovered = new HashSet(); uint time = 0; var output = new Dictionary>(); foreach (var node in Nodes) { output.Add(node, new Dictionary()); } void dfsHelper(TNode v) { discovered.Add(v); time++; output[v].Add(SearchSymbol.start, time); foreach (var neighbor in Neighbors(v)) { if (!discovered.Contains(neighbor)) { dfsHelper(neighbor); } } time++; output[v].Add(SearchSymbol.finish, time); } foreach (var node in Nodes) { if (!discovered.Contains(node)) { dfsHelper(node); } } return output; } public bool Cyclic() { return StronglyConnectedComponents().Any((scc) => scc.Count() > 1); } public IEnumerable TopologicalSort() { var dfs = NodeDFS(); var priority = new SortedList(); foreach (var entry in dfs) { priority.Add(entry.Value[SearchSymbol.finish], entry.Key); } return priority.Values.Reverse(); } public IEnumerable> StronglyConnectedComponents() { var preorder = new Dictionary(); var lowlink = new Dictionary(); var sccFound = new Dictionary(); var sccQueue = new Stack(); var result = new List>(); uint preorderCounter = 0; foreach (var source in Nodes) { if (!sccFound.ContainsKey(source)) { var queue = new Stack(); queue.Push(source); while (queue.Count > 0) { var v = queue.Peek(); if (!preorder.ContainsKey(v)) { preorderCounter++; preorder[v] = preorderCounter; } var done = true; var vNeighbors = Neighbors(v); foreach (var w in vNeighbors) { if (!preorder.ContainsKey(w)) { queue.Push(w); done = false; break; } } if (done) { lowlink[v] = preorder[v]; foreach (var w in vNeighbors) { if (!sccFound.ContainsKey(w)) { if (preorder[w] > preorder[v]) { lowlink[v] = Math.Min(lowlink[v], lowlink[w]); } else { lowlink[v] = Math.Min(lowlink[v], preorder[w]); } } } queue.Pop(); if (lowlink[v] == preorder[v]) { sccFound[v] = true; var scc = new List { v }; while (sccQueue.Count > 0 && preorder[sccQueue.Peek()] > preorder[v]) { var k = sccQueue.Pop(); sccFound[k] = true; scc.Add(k); } result.Add(scc); } else { sccQueue.Push(v); } } } } } return result; } public IEnumerable> SimpleCycles() { void unblock(TNode thisnode, HashSet blocked, Dictionary> B) { var stack = new Stack(); stack.Push(thisnode); while (stack.Count > 0) { var node = stack.Pop(); if (blocked.Contains(thisnode)) { blocked.Remove(thisnode); if (B.ContainsKey(node)) { foreach (var n in B[node]) { if (!stack.Contains(n)) { stack.Push(n); } } B[node].Clear(); } } } } List> result = new List>(); var subGraph = Clone(); var sccs = new Stack>(); foreach (var scc in StronglyConnectedComponents()) { sccs.Push(scc); } while (sccs.Count > 0) { var scc = new Stack(sccs.Pop()); var startNode = scc.Pop(); var path = new Stack(); path.Push(startNode); var blocked = new HashSet { startNode }; var closed = new HashSet(); var B = new Dictionary>(); var stack = new Stack>>(); stack.Push(Tuple.Create(startNode, new Stack(subGraph.Neighbors(startNode)))); while (stack.Count > 0) { var entry = stack.Peek(); var thisnode = entry.Item1; var neighbors = entry.Item2; if (neighbors.Count > 0) { var nextNode = neighbors.Pop(); if (nextNode.Equals(startNode)) { var resultPath = new List(); foreach (var v in path) { resultPath.Add(v); } result.Add(resultPath); foreach (var v in path) { closed.Add(v); } } else if (!blocked.Contains(nextNode)) { path.Push(nextNode); stack.Push(Tuple.Create(nextNode, new Stack(subGraph.Neighbors(nextNode)))); closed.Remove(nextNode); blocked.Add(nextNode); continue; } } if (neighbors.Count == 0) { if (closed.Contains(thisnode)) { unblock(thisnode, blocked, B); } else { foreach (var neighbor in subGraph.Neighbors(thisnode)) { if (!B.ContainsKey(neighbor)) { B[neighbor] = new HashSet(); } B[neighbor].Add(thisnode); } } stack.Pop(); path.Pop(); } } subGraph.RemoveNode(startNode); var H = subGraph.SubGraph(scc.ToArray()); var HSccs = H.StronglyConnectedComponents(); foreach (var HScc in HSccs) { sccs.Push(HScc); } } return result.Distinct(new SimpleCycleComparer()); } public DirectedGraph Clone() { var clone = new DirectedGraph(); clone.AddNodes(Nodes.ToArray()); foreach (var v in Nodes) { foreach (var n in Neighbors(v)) { clone.AddEdge(v, n, EdgeData((v, n))); } } return clone; } public DirectedGraph SubGraph(params TNode[] subVertices) { var subGraph = new DirectedGraph(); subGraph.AddNodes(subVertices.ToArray()); foreach (var n in Nodes) { if (Nodes.Contains(n)) { var neighbors = Neighbors(n); foreach (var u in neighbors) { if (subVertices.Contains(u)) { subGraph.AddEdge(n, u, EdgeData((n, u))); } } } } return subGraph; } public void Clear() { nodes.Clear(); neighbors.Clear(); } } }