public static bool HasCircle(INewGraph graph) { var queue = new Queue <IVertex>(); var visited = new HashSet <IVertex>(); var parent = new Dictionary <IVertex, IVertex>(); queue.Enqueue(graph.First()); while (queue.Count > 0) { var node = queue.Dequeue(); visited.Add(node); foreach (var next in graph.GetNeighborVertices(node)) { if (visited.Contains(next)) { continue; } queue.Enqueue(next); var px = Find(parent, node); var py = Find(parent, next); if (px.Equals(py)) { return(true); } Union(parent, node, next); } } return(false); }
public static INewGraph KruskalMST(INewGraph graph) { LogTool.AssertIsTrue(graph.Edges.First() is IWeightedEdge); var ret = graph.Factory.CreateGraph(); var edges = graph.Edges.OrderBy(e => (e as IWeightedEdge).Weight); var currentEdges = new List <IEdge>(); foreach (var e in edges) { currentEdges.Add(e); if (GraphTools.HasCircle(currentEdges)) { currentEdges.RemoveAt(currentEdges.Count - 1); } else { var nv1 = ret.AddVertex(e.Vertex.Clone() as IVertex); var nv2 = ret.AddVertex(e.OtherVertex.Clone() as IVertex); ret.AddEdge(nv1, nv2); } } return(ret); }
public static INewGraph Generate(INewGraph graph, IVertex first = null) { var ret = graph.Factory.CreateGraph(); var queue = new Queue <IVertex>(); var visited = new HashSet <IVertex>(); queue.Enqueue(first == null ? graph.First() : first); while (queue.Count > 0) { var node = queue.Dequeue(); visited.Add(node); var v1 = ret.AddVertex(node.Clone() as IVertex); foreach (var next in graph.GetNeighborVertices(node)) { if (visited.Contains(next)) { continue; } visited.Add(next); queue.Enqueue(next); var v2 = ret.AddVertex(next.Clone() as IVertex); ret.AddEdge(v1, v2); } } return(ret); }
public static void CalculateVerticeWeight(INewGraph graph) { debug.Clear(); foreach (var v in graph.Vertices) { LogTool.AssertIsTrue(v is IVertex); UpdateEdgeCost(graph, v as IVertex); } }
public static void RemoveMinCostVertex(INewGraph graph) { var min = graph.Vertices.Cast <IVertex>().OrderBy(v => v.CostTo.cost).FirstOrDefault(); if (min == default) { return; } MergeVertexTo(graph, min, min.CostTo.to); }
public static IGraphPath GetPath(INewGraph graph, IVertex from, IVertex to) { var ret = new GraphPath(); var visited = new HashSet <IVertex>(); var found = GetPathDFS(graph, from, to, ret, visited); if (found) { return(ret); } return(default);
protected static void MergeVertexTo(INewGraph graph, IVertex from, IVertex to) { LogTool.AssertIsFalse(from.Equals(to)); var fromNeighbors = graph.GetNeighborVertices(from as Common.IVertex).ToList(); foreach (var n in fromNeighbors) { var e = graph.GetEdge(from as Common.IVertex, n); LogTool.AssertNotNull(e); graph.Remove(e); if (n.Equals(to)) { continue; } graph.AddEdge(n, to as Common.IVertex); } graph.Remove(from as Common.IVertex); foreach (var n in fromNeighbors) { UpdateEdgeCost(graph, n as IVertex); } }
public static void Traverse(INewGraph graph) { }