Example #1
0
        public static int ComputeShortestPath(IDirectedGraph <int> graph, int startVertex, int endVertex)
        {
            if (startVertex == endVertex)
            {
                return(0);
            }
            // Key - Node, Value - node distance from startVertex
            var exploredVertices = new Dictionary <int, int> {
                { startVertex, 0 }
            };
            var queue = new Queue <int>();

            queue.Enqueue(startVertex);

            while (queue.Any())
            {
                int v = queue.Dequeue();
                foreach (int w in graph.GetAdjacentVertices(v))
                {
                    if (!exploredVertices.ContainsKey(w))
                    {
                        int dist = exploredVertices[v] + 1;
                        exploredVertices.Add(w, dist);
                        queue.Enqueue(w);
                    }
                }
            }
            return(exploredVertices.ContainsKey(endVertex) ? exploredVertices[endVertex] : int.MinValue);
        }
Example #2
0
        private static void DfsFindSccs(IDirectedGraph <int> graph,
                                        int startVertex,
                                        HashSet <int> exploredVertices,
                                        List <int> sccs)
        {
            var stack = new Stack <int>();

            stack.Push(startVertex);

            while (stack.Any())
            {
                int v = stack.Peek();
                if (!exploredVertices.Contains(v))
                {
                    exploredVertices.Add(v);
                }

                bool hasUnexploredNeighbours = false;
                foreach (int w in graph.GetAdjacentVertices(v))
                {
                    if (!exploredVertices.Contains(w))
                    {
                        hasUnexploredNeighbours = true;
                        stack.Push(w);
                        break;
                    }
                }
                if (!hasUnexploredNeighbours)
                {
                    sccs.Add(stack.Pop());
                }
            }
        }
        /// <summary>
        /// Implementacija Bellman-Ford algoritma za pronalazenje najkracih putanja u
        /// tezinskom, orijentisanom ili neorijentisanom grafu sa ili bez ciklusa.
        /// </summary>
        /// <param name="graph"></param>
        /// <param name="start"></param>
        /// <returns>true u slucaju da je pronadjeno negativno pojacanje, inace false</returns>
        public bool BellmanFord(IDirectedGraph <TVertex, TEdge> graph, TVertex start)
        {
            //Inicijalizujemo kolekcije
            Initialize(graph, start);

            //Prolazimo kroz sve grane grafa |V|-1 puta i osvezavamo rastojanja izmedju nod-ova.
            //U slucaju da nema ciklusa sa kruznim pojacanjem, to ce da garantuje da su sve najkrace
            //putanje otkrivene (pogledati teorijsku osnovu algoritma).
            for (int i = 0; i < graph.VertexCount - 1; i++)
            {
                foreach (TEdge edge in graph.Edges)
                {
                    OnExamineVertex(edge.Source);

                    if (RelaxEdge(edge))
                    {
                        OnEdgeRelaxed(edge);
                    }
                }
            }

            //Provera na negativne cikluse, ako se nakon |V|-1 iteracija javlja novo osvezenje
            //grane u grafu, to je potvrda da postoje takvi ciklusi.
            foreach (TEdge edge in graph.Edges)
            {
                if (RelaxEdge(edge))
                {
                    return(true);
                }
            }

            return(false);
        }
Example #4
0
        public StrongComponentChecker(IDirectedGraph <NodeType, EdgeType> graph)
        {
            this.graph = graph;
            dfs        = new DepthFirstSearch <NodeType, EdgeType>(graph);
            CanCreateNodeData <NodeType> data = (CanCreateNodeData <NodeType>)graph;

            DiscoverTime      = data.CreateNodeData <int>(0);
            RootDiscoverTime  = data.CreateNodeData <int>(0);
            dfs.DiscoverNode += delegate(NodeType node)
            {
                DiscoverTime[node]     = time;
                RootDiscoverTime[node] = time;
                time++;
            };
            dfs.BackEdge       += ProcessEdge2;
            dfs.CrossEdge      += ProcessEdge2;
            dfs.FinishTreeEdge += ProcessEdge;
            dfs.FinishNode     += delegate(NodeType node)
            {
                int thisRootDiscoverTime = RootDiscoverTime[node];
                if (thisRootDiscoverTime < DiscoverTime[node])
                {
                    // not a root
                }
                else
                {
                    // root of a component
                    if (thisRootDiscoverTime != 0)
                    {
                        IsStrong = false;
                    }
                }
            };
        }
 public BackwardScheduler(Stack <INode> rootNodes, IDirectedGraph <INode> orderOperationGraph,
                          bool clearOldTimes)
 {
     _S = rootNodes;
     _orderOperationGraph = orderOperationGraph;
     _clearOldTimes       = clearOldTimes;
 }
        /// <summary>
        /// Dijsktra algoritam za trazenje najmanjeg rastojanja i odgovarajucih
        /// putanja. Graf mora imati sve pozitivne tezine grana ali moze da bude neusmeren
        /// i/ili da sadrzi cikluse (petlje).
        /// </summary>
        /// <param name="start"></param>
        public void Dijkstra_shortest_path(IDirectedGraph <TVertex, TEdge> graph, TVertex start)
        {
            //Inicijalizujemo kolekcije
            Initialize(graph, start);
            minQueue.Clear();
            minQueue.Insert(start);

            while (minQueue.Count > 0)
            {
                TVertex u = minQueue.Remove();
                if (vertexColors[u] == VertexColor.Black)
                {
                    continue;
                }

                vertexColors[u] = VertexColor.Black;
                OnExamineVertex(u);

                foreach (TEdge edge in graph.OutEdges(u))
                {
                    if (RelaxEdge(edge))
                    {
                        vertexColors[edge.Target] = VertexColor.Gray;
                        minQueue.Insert(edge.Target);
                        OnEdgeRelaxed(edge);
                    }
                }
            }
        }
Example #7
0
        private void ScheduleBackwardSecond(IDirectedGraph <INode> orderOperationGraph)
        {
            INodes childRootNodes = new Nodes();

            foreach (var rootNode in orderOperationGraph.GetRootNodes())
            {
                if (rootNode.GetEntity().GetType() != typeof(CustomerOrderPart))
                {
                    continue;
                }

                Providers childProviders = ZppConfiguration.CacheManager.GetAggregator()
                                           .GetAllChildProvidersOf((Demand)rootNode.GetEntity());
                if (childProviders == null || childProviders.Count() > 1)
                {
                    throw new MrpRunException(
                              "After Mrp1 a CustomerOrderPart MUST have exact one child.");
                }

                childRootNodes.AddAll(childProviders.ToNodes());
            }

            IBackwardsScheduler backwardsScheduler =
                new BackwardScheduler(childRootNodes.ToStack(), orderOperationGraph, false);

            backwardsScheduler.ScheduleBackward();
        }
Example #8
0
        private static IList <TNode> ReconstructPath(IDirectedGraph <TNode, TEdge> graph, IReadOnlyDictionary <string, string> cameFrom, string currentNodeId)
        {
            var path = new List <TNode>();

            ReconstructPath(graph, cameFrom, currentNodeId, path);
            return(path);
        }
        public void ReplaceNodeByDirectedGraph(Id nodeId, IDirectedGraph <INode> graphToInsert)
        {
            INodes predecessors = GetPredecessorNodes(nodeId);
            INodes successors   = GetSuccessorNodes(nodeId);

            RemoveNode(nodeId, false);
            // predecessors --> roots
            if (predecessors != null)
            {
                foreach (var predecessor in predecessors)
                {
                    foreach (var rootNode in graphToInsert.GetRootNodes())
                    {
                        AddEdge(new Edge(predecessor, rootNode));
                    }
                }
            }

            // leafs --> successors
            if (successors != null)
            {
                foreach (var leaf in graphToInsert.GetLeafNodes())
                {
                    foreach (var successor in successors)
                    {
                        AddEdge(new Edge(leaf, successor));
                    }
                }
            }

            // add all edges from graphToInsert
            AddEdges(graphToInsert.GetEdges());
        }
Example #10
0
        private void DFS(IDirectedGraph graph, int vertex)
        {
            onStack[vertex]     = true;
            isConnected[vertex] = true;

            foreach (int v in graph.Adjacent(vertex))
            {
                if (HasCycle())
                {
                    return;
                }

                if (!isConnected[v])
                {
                    edgeTo[v] = vertex;
                    DFS(graph, v);
                }
                // 如果当前相邻顶点被标记过,并且在递归调用栈上,说明路径又回到了之前的顶点,也就是出现环路
                else if (onStack[v])
                {
                    cycle = new Stack <int>();

                    // 把路径上的所有顶点记录下来
                    for (int i = vertex; i != v; i = edgeTo[i])
                    {
                        cycle.Push(i);
                    }

                    cycle.Push(v);
                    cycle.Push(vertex);
                }
            }

            onStack[vertex] = false;
        }
Example #11
0
        private void Visit(
            IDirectedGraph <TVertex, TEdge> graph,
            TVertex vertex,
            SearchState <TVertex, TEdge> state,
            Queue <TVertex> output)
        {
            if (state.HasPermanentMark(vertex))
            {
                return;
            }

            if (state.HasTemporaryMark(vertex))
            {
                throw new CyclicGraphsNotSupportedException();
            }

            state.SetTemporaryMark(vertex);

            foreach (var connectedVertex in graph.OutEdges(vertex).Select(e => e.To))
            {
                this.Visit(graph, connectedVertex, state, output);
            }

            state.RemoveTemporaryMark(vertex);
            state.SetPermanentMark(vertex);
            output.Enqueue(vertex);
        }
        private void solve(IDirectedGraph g)
        {
            result = new List <int>();
            Degrees degrees_info = new Degrees(g);

            int[] degrees = new int[g.V];
            for (int i = 0; i < g.V; ++i)
            {
                degrees[i] = degrees_info.InDegree(i);
            }
            Queue <int> starts = new Queue <int>();

            foreach (Int32 s in degrees_info.Sources())
            {
                starts.Enqueue(s);
            }
            //只要还有顶点
            while (starts.Count > 0)
            {
                Int32 v = starts.Dequeue();
                result.Add(v);
                foreach (var w in g.Adj(v))
                {
                    //删除这个顶点的指出的边,因为这个顶点已经被删除了
                    --degrees[w];
                    if (degrees[w] == 0)
                    {
                        //下一个拓扑排序的顺序
                        starts.Enqueue(w);
                    }
                }
            }
        }
Example #13
0
        public PathFinder(IDirectedGraph <NodeType> graph)
        {
            this.graph = graph;
            CanCreateNodeData <NodeType> data = (CanCreateNodeData <NodeType>)graph;

            isBlocked = data.CreateNodeData <bool>(false);
        }
Example #14
0
        public GanttChart(IDirectedGraph <INode> orderOperationGraph)
        {
            Dictionary <Id, List <Interval> > groups = new Dictionary <Id, List <Interval> >();

            foreach (var graphNode in orderOperationGraph.GetNodes())
            {
                IScheduleNode node = graphNode.GetNode().GetEntity();
                if (node.GetType() != typeof(ProductionOrderOperation) && node.GetType() != typeof(PurchaseOrderPart))
                {
                    continue;
                }
                GanttChartBar ganttChartBar = new GanttChartBar();

                ganttChartBar.operation   = node.GetId().ToString();
                ganttChartBar.operationId = node.GetId().ToString();
                ganttChartBar.resource    = DetermineFreeGroup(groups,
                                                               new Interval(node.GetId(), node.GetStartTimeBackward(), node.GetEndTimeBackward())).ToString();

                ;
                ganttChartBar.start = node.GetStartTimeBackward().GetValue().ToString();
                ganttChartBar.end   = node.GetEndTimeBackward().GetValue().ToString();

                ganttChartBar.groupId = ganttChartBar.resource;

                AddGanttChartBar(ganttChartBar);
            }
        }
Example #15
0
        public static void buildGraphFromInitialState(IDirectedGraph <char> graph, string rawGraphData)
        {
            try
            {
                string[] verticeEdgeData = rawGraphData.Split(",");

                foreach (string verticeEdge in verticeEdgeData)
                {
                    string verticeEdgeTrimmed = verticeEdge.Trim();

                    char  vertecie1 = Char.Parse(verticeEdgeTrimmed.Substring(0, 1));
                    char  vertecie2 = Char.Parse(verticeEdgeTrimmed.Substring(1, 1));
                    float weight    = float.Parse(verticeEdgeTrimmed.Substring(2, verticeEdgeTrimmed.Length - 2));

                    graph.AddVertex(vertecie1);
                    graph.AddVertex(vertecie2);

                    graph.AddEdge(vertecie1, vertecie2, weight);
                }
            }
            catch (Exception)
            {
                Console.WriteLine("The graph data was passed in an incorrect form.\n\tFor a node A that connects to a node B with a weight of 5 pass data in like 'AB5'.\n\tSeparate data by columns: 'AB5, AC2'");
                throw;
            }
        }
Example #16
0
 private void dfs(IDirectedGraph digraph, int v)
 {
     onStack[v] = true;
     marked[v]  = true;
     foreach (int w in digraph.Adj(v))
     {
         if (HasCycle())
         {
             return;
         }
         else if (!marked[w])
         {
             edgeTo[w] = v;
             dfs(digraph, w);
         }
         else if (onStack[w])//如果访问过且在一个路径中
         {
             cycle = new Stack <int>();
             for (int x = v; x != w; x = edgeTo[x])
             {
                 cycle.Push(x);//把前驱放入栈中直到环的起点的后继
             }
             cycle.Push(w);
             cycle.Push(v);//为何从v开始呢?因为v->w是有连接的。此时栈顶和栈底都是一个
         }
     }
     onStack[v] = false;//循环结束,不是一条栈上链的
 }
Example #17
0
        public void TestAsString()
        {
            INode[] nodes = EntityFactory.CreateDummyNodes(7);
            IDirectedGraph <INode> directedGraph = CreateBinaryDirectedGraph(nodes);

            Assert.True(directedGraph.ToString() != null,
                        "AsString() must work in unit tests without a database.");
        }
Example #18
0
        private void ScheduleBackward(Stack <INode> rootNodes,
                                      IDirectedGraph <INode> orderOperationGraph, bool clearOldTimes)
        {
            IBackwardsScheduler backwardsScheduler =
                new BackwardScheduler(rootNodes, orderOperationGraph, clearOldTimes);

            backwardsScheduler.ScheduleBackward();
        }
Example #19
0
        public CycleFinder(IDirectedGraph <NodeType> graph)
        {
            this.graph = graph;
            CanCreateNodeData <NodeType> data = (CanCreateNodeData <NodeType>)graph;

            isBlocked      = data.CreateNodeData <bool>(false);
            blockedSources = data.CreateNodeData <Set <NodeType> >(null);
        }
Example #20
0
        public DFSCost(IDirectedGraph graph, int start)
        {
            this.graph = graph;
            this.start = start;

            this.visited = new bool[graph.Size];
            paths        = new Dictionary <int, IEnumerable <int> >();
        }
Example #21
0
 private static void ReconstructPath(IDirectedGraph <TNode, TEdge> graph, IReadOnlyDictionary <string, string> cameFrom, string currentNodeId, ICollection <TNode> thelist)
 {
     if (cameFrom.ContainsKey(currentNodeId))
     {
         ReconstructPath(graph, cameFrom, cameFrom[currentNodeId], thelist);
     }
     thelist.Add(graph[currentNodeId]);
 }
        public static bool ContainsVertex <T>(this IDirectedGraph <T> graph, T value) where T : IEquatable <T>
        {
            if (graph is null)
            {
                throw new ArgumentNullException(nameof(graph));
            }

            return(graph[value] != default);
        }
        public DepthFirstSearchGraphEnumerator(IDirectedGraph <TVertex> graph, TVertex origin)
        {
            Graph   = graph;
            Origin  = origin;
            Stack   = new Stack <TVertex>();
            Visited = new HashSet <TVertex>();

            Initialize();
        }
Example #24
0
        /// <inheritdoc />
        public IEnumerable <TVertex> Execute(IDirectedGraph <TVertex, TEdge> graph, TVertex startVertex)
        {
            var output = new Queue <TVertex>(graph.VertexCount);
            var state  = SearchState.Create(graph);

            this.Visit(graph, startVertex, state, output);

            return(output);
        }
Example #25
0
        public BreadthFirstSearchGraphEnumerator(IDirectedGraph <TVertex> graph, TVertex origin)
        {
            Graph   = graph;
            Origin  = origin;
            Queue   = new Queue <TVertex>();
            Visited = new HashSet <TVertex>();

            Initialize();
        }
Example #26
0
 protected void Initialize(IDirectedGraph <TVertex, TEdge> graph)
 {
     this.graph = graph;
     vertexColors.Clear();
     foreach (TVertex u in graph.Vertices)
     {
         vertexColors.Add(u, VertexColor.White);
     }
 }
Example #27
0
        public IList <TNode> ShortestPath(IDirectedGraph <TNode, TEdge> graph, TNode source, TNode goal)
        {
            if (source == null || goal == null)
            {
                return(null);
            }

            var visited  = new HashSet <string>();
            var queue    = new KeyValueHeap <string, int>(_comparer);
            var cameFrom = new Dictionary <string, string>();

            var gScore = new Dictionary <string, int>();
            var fScore = new Dictionary <string, int>();

            queue.Insert(source.Id, 0);
            gScore[source.Id] = 0;
            fScore[source.Id] = gScore[source.Id] + Heuristic.Evaluate(source, goal);

            while (!queue.Empty)
            {
                var current = graph[queue.RemoveRootKey()];
                if (current.Id == goal.Id)
                {
                    return(ReconstructPath(graph, cameFrom, current.Id));
                }

                visited.Add(current.Id);
                foreach (var neighbor in graph.Outgoing(current).Where(neighbor => !visited.Contains(neighbor.Id)))
                {
                    var score = gScore[current.Id] + graph[current, neighbor].Weight;

                    if (!queue.ContainsKey(neighbor.Id) || score < gScore[neighbor.Id])
                    {
                        cameFrom[neighbor.Id] = current.Id;
                        gScore[neighbor.Id]   = score;

                        var tmpFScore = score + Heuristic.Evaluate(neighbor, goal);
                        if (queue.ContainsKey(neighbor.Id))
                        {
                            if (tmpFScore < fScore [neighbor.Id])
                            {
                                fScore[neighbor.Id] = tmpFScore;
                                queue.SetValue(neighbor.Id, tmpFScore);
                            }
                        }
                        else
                        {
                            fScore[neighbor.Id] = tmpFScore;
                            queue.Insert(neighbor.Id, fScore[neighbor.Id]);
                        }
                    }
                }
            }

            return(null);
        }
        public static bool SetBidirectionalEdge <T>(this IDirectedGraph <T> graph, Vertex <T> firstVertex, Vertex <T> secondVertex, int weight) where T : IEquatable <T>
        {
            if (graph is null)
            {
                throw new ArgumentNullException(nameof(graph));
            }

            return(graph.SetEdge(firstVertex, secondVertex, weight) &&
                   graph.SetEdge(secondVertex, firstVertex, weight));
        }
Example #29
0
 /// <summary>
 /// Adds sequence of vertices to the graph.
 /// </summary>
 /// <typeparam name="V"></typeparam>
 /// <typeparam name="E"></typeparam>
 /// <param name="graph"></param>
 /// <param name="vertices"></param>
 public static void AddVertices <V, E>(this IDirectedGraph <V, E> graph, IEnumerable <V> vertices)
 {
     using (Trace.Entering())
     {
         foreach (V vertex in vertices)
         {
             graph.AddVertex(vertex);
         }
     }
 }
Example #30
0
        public void TestRemoveNode()
        {
            INode[] nodes = EntityFactory.CreateDummyNodes(6);
            IDirectedGraph <INode> directedGraph = CreateBinaryDirectedGraph(nodes);
            INode nodeToRemove = nodes[2];

            directedGraph.RemoveNode(nodeToRemove, false);

            Assert.True(directedGraph.Contains(nodeToRemove) == false);
        }
 public TopologicalSort(IDirectedGraph g) : base(g)
 {
     digraph = g;
 }
 public StronglyConnectedComponents(IDirectedGraph g) {
     graph = g;
     dfs = new DepthFirstSearch(g);
     dfs.VisitingVertex += Dfs_VisitingVertex;
 }