示例#1
0
        public void DistanceIsRecalculatedWhenCheaperPathIsFound()
        {
            var sut = new BellmanFord();

            var graph =
                new[]
            {
                new WeightedGraphVertex
                {
                    Edges = new System.Collections.Generic.List <WeightedGraphNodeEdge>
                    {
                        new WeightedGraphNodeEdge
                        {
                            Weight = 1,
                            To     = 1,
                            From   = 0
                        },
                        new WeightedGraphNodeEdge
                        {
                            Weight = 5,
                            To     = 2,
                            From   = 0
                        }
                    }
                },
                new WeightedGraphVertex
                {
                    Edges = new System.Collections.Generic.List <WeightedGraphNodeEdge>
                    {
                        new WeightedGraphNodeEdge
                        {
                            Weight = 2,
                            To     = 2,
                            From   = 1
                        }
                    }
                },
                new WeightedGraphVertex
                {
                }
            };

            var(minDistance, path) = sut.MinDistance(graph, 0, 2);

            Assert.Equal(3, minDistance);
            Assert.Equal(1, path[2]);
        }
示例#2
0
        public void DistanceToItselfIsZero()
        {
            var sut = new BellmanFord();

            var graph =
                new[]
            {
                new WeightedGraphVertex
                {
                }
            };

            var(minDistance, path) = sut.MinDistance(graph, 0, 0);

            Assert.Equal(0, minDistance);
            Assert.Equal(0, path[0]);
        }
    // Use this for initialization
    void Start()
    {
        string name = "testWeightG1.txt";
//		name = "testShortPath.txt";
        string url = FileHelper.FileNameHelper(name);
        WeightSpareGraph <float> sGraph = null;

        ReadWeightGraph.ReadGraphFromFile(url, out sGraph, false);
        sGraph.print();
        Dijkstra dijkstra = new Dijkstra(sGraph, 0);

        dijkstra.ShowAllPath();

        BellmanFord bellmanFord = new BellmanFord(sGraph, 0);

        bellmanFord.showAllPath();
    }
示例#4
0
        public override IEnumerable <object> Solve(TextReader inputStream)
        {
            var(nodeCount, edgeCount, penalty) = inputStream.ReadValue <int, int, int>();
            var graph = new WeightedGraph(nodeCount);

            for (int i = 0; i < edgeCount; i++)
            {
                var(from, to, coin) = inputStream.ReadValue <int, int, int>();
                from--;
                to--;
                graph.AddEdge(new WeightedEdge(from, to, penalty - coin));
            }

            var bf = new BellmanFord <BasicNode, WeightedEdge>(graph);

            var(distances, negativeCycles) = bf.GetDistancesFrom(new BasicNode(0));

            if (negativeCycles[^ 1])
        public void GrokkinAlgortihms_Ex_7_1_C()
        {
            // Arrange
            var startNode = new Node("Start");
            var aNode     = new Node("A");
            var bNode     = new Node("B");
            var cNode     = new Node("C");
            var endNode   = new Node("End");

            var graph = new Graph(startNode, endNode);
            var edges = graph.Add(startNode);

            edges.Add(new Edge {
                Node = aNode, Weight = 2
            });
            edges.Add(new Edge {
                Node = bNode, Weight = 2
            });
            edges = graph.Add(aNode);
            edges.Add(new Edge {
                Node = cNode, Weight = 2
            });
            edges.Add(new Edge {
                Node = endNode, Weight = 2
            });
            edges = graph.Add(bNode);
            edges.Add(new Edge {
                Node = aNode, Weight = 2
            });
            edges = graph.Add(cNode);
            edges.Add(new Edge {
                Node = bNode, Weight = -1
            });
            edges.Add(new Edge {
                Node = endNode, Weight = 2
            });
            graph.Add(endNode);

            // Act
            var shortestPath = BellmanFord.Run(graph);

            // Assert
            Assert.Equal(new[] { startNode, aNode, endNode }, shortestPath);
        }
示例#6
0
        public void ABC137Test_FromEdges(string testCaseName)
        {
            ABC137Test_Core(testCaseName, (nodesCount, edgesCount, penalty, io) =>
            {
                var graph       = new WeightedGraph(nodesCount);
                var bellmanFord = new BellmanFord(nodesCount);

                for (int i = 0; i < edgesCount; i++)
                {
                    var abc = io.ReadIntArray(3);
                    var a   = abc[0] - 1;
                    var b   = abc[1] - 1;
                    var c   = abc[2];
                    bellmanFord.AddEdge(a, b, penalty - c);
                }

                return(bellmanFord);
            });
        }
示例#7
0
        public ExchangeRateResponse ExchangeRate(ExchangeRateRequest request)
        {
            lock (lockTheEntireGraph)
            {
                var response = new ExchangeRateResponse();

                var spt = new BellmanFord <ExchangeCurrency>(graph, request.Source);
                if (spt.HasNegativeCycle())
                {
                    response.IsCycle = true;

                    var cycle = spt.NegativeCycle();
                    response.Cycle = EdgesToVertexes(cycle);
                    return(response); // TODO: cycle ==> arbitrage opportunity
                }
                if (spt.HasPathTo(request.Destination))
                {
                    response.IsHasPath = true;

                    var    path           = spt.PathTo(request.Destination);
                    var    vertexesOnPath = EdgesToVertexes(path);
                    double rate           = 1;
                    foreach (var edge in path)
                    {
                        rate *= Math.Exp(-edge.Weight);
                    }

                    response.Source      = request.Source;
                    response.Destination = request.Destination;
                    response.Rate        = rate;
                    response.Path        = vertexesOnPath;
                    return(response);
                }
                if (!spt.HasPathTo(request.Destination))
                {
                    response.IsHasPath = false;
                    return(response);
                }

                throw new NotImplementedException();
            }
        }
示例#8
0
        // Get the shortest solution according to the specified route settings
        public List <Edge> GetSolution()
        {
            try
            {
                var shortestRoute = Settings.ShortestRouteSetting;
                if (shortestRoute == ShortestRoute.BellmanFord)
                {
                    var bellmanFord = new BellmanFord(this);
                    return(bellmanFord.GetPath(RootCube, IsSolved()));
                }

                var dijkstra = new Dijkstra(this);
                dijkstra.Execute(RootCube);
                return(dijkstra.GetPath(SolvedNode));
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
        }
示例#9
0
        protected override void Calculate()
        {
            var res = double.NaN;

            if (_currencyId != -1)
            {
                var graphSnapshot = _symbolGraph.GetSnapshot(edge => double.IsNaN(edge.ReverseWeight) ? null : new Edge <CurrencyNode>(edge.From, edge.To, edge.ReverseWeight));
                var searchResult  = BellmanFord <CurrencyNode, Edge <CurrencyNode> > .CalculateShortestPaths(graphSnapshot, _pathLogic, _currencyId);

                res = 0;
                foreach (var nodeId in _currencyListIds)
                {
                    res += !searchResult.Distance[nodeId].E(_pathLogic.UnreachableValue)
                        ? -searchResult.Distance[nodeId]
                        : double.NaN;
                }
            }

            Output[0] = res;
        }
示例#10
0
        static void Main(string[] args)
        {
            var graph       = new Graph(dataSets[CURRENT_DATASET_INDEX]);
            var source      = graph.NodeMap[START_LABEL];
            var destination = graph.NodeMap[END_LABEL];

            switch (CURRENT_TASK)
            {
            case Task.RoyFloyd:
            {
                var solver = new RoyFloyd(graph.Nodes.Count);

                solver.Run(graph);
                solver.PrintMinPath(graph, source, destination);

                break;
            }

            case Task.Dijkstra:
            {
                var solver   = new Dijkstra(graph);
                var distance = solver.Run(source);

                PrintDistance(graph, distance);

                break;
            }

            case Task.BellmanFord:
            {
                var solver   = new BellmanFord(graph);
                var distance = solver.Run(source);

                PrintDistance(graph, distance);

                break;
            }

            default: break;
            }
        }
        public void BellmanFordFunc_EqualGraphsDistancesSums_ReturnsIncorrectDistancesSum()
        {
            //Graph init

            var graph = new Graph();

            var nodeOne   = new Node("One");
            var nodeTwo   = new Node("Two");
            var nodeThree = new Node("Three");
            var nodeFour  = new Node("Four");
            var nodeFive  = new Node("Five");
            var nodeSix   = new Node("Six");
            var nodeSeven = new Node("Seven");


            graph.nodes.AddRange(new Node[] { nodeOne, nodeTwo, nodeThree, nodeFour, nodeFive, nodeSix, nodeSeven });

            graph.AddConnection(new Edge(nodeOne, nodeTwo, 3));
            graph.AddConnection(new Edge(nodeOne, nodeThree, 5));
            graph.AddConnection(new Edge(nodeTwo, nodeThree, 4));
            graph.AddConnection(new Edge(nodeTwo, nodeFour, 3));
            graph.AddConnection(new Edge(nodeThree, nodeFive, 2));
            graph.AddConnection(new Edge(nodeFour, nodeFive, 4));
            graph.AddConnection(new Edge(nodeOne, nodeSix, 13));
            graph.AddConnection(new Edge(nodeFive, nodeSix, 3));
            graph.AddConnection(new Edge(nodeSix, nodeSeven, 2));
            graph.AddConnection(new Edge(nodeFive, nodeSeven, 1));
            //graph.AddConnection(new Edge(nodeTwo, nodeSeven, 4)); // Commented one Edge for testing

            //Expected sum init

            int sumExpected = 37;

            //BellmanFord check

            int sumActual = BellmanFord.BellmanFordFunc(graph, nodeOne);

            //Assert

            Assert.AreNotEqual(sumExpected, sumActual);
        }
示例#12
0
        public void DistanceToGrandNeighborNodeIsEqualSumOfEdgesWeight()
        {
            var sut = new BellmanFord();

            var graph =
                new[]
            {
                new WeightedGraphVertex
                {
                    Edges = new System.Collections.Generic.List <WeightedGraphNodeEdge>
                    {
                        new WeightedGraphNodeEdge
                        {
                            Weight = 1,
                            To     = 1,
                            From   = 0
                        }
                    }
                },
                new WeightedGraphVertex
                {
                    Edges = new System.Collections.Generic.List <WeightedGraphNodeEdge>
                    {
                        new WeightedGraphNodeEdge
                        {
                            Weight = 2,
                            To     = 2,
                            From   = 1
                        }
                    }
                },
                new WeightedGraphVertex
                {
                }
            };

            var(minDistance, path) = sut.MinDistance(graph, 0, 2);
            Assert.Equal(3, minDistance);
            Assert.Equal(0, path[1]);
            Assert.Equal(1, path[2]);
        }
        protected override void Calculate()
        {
            var res = double.NaN;

            if (_currencyId != -1 && Account.Type == AccountTypes.Cash)
            {
                var graphSnapshot = _symbolGraph.GetSnapshot(edge => double.IsNaN(edge.ReverseWeight) ? null : new Edge <CurrencyNode>(edge.From, edge.To, edge.ReverseWeight));
                var searchResult  = BellmanFord <CurrencyNode, Edge <CurrencyNode> > .CalculateShortestPaths(graphSnapshot, _pathLogic, _currencyId);

                res = 0;
                foreach (var asset in Account.Assets)
                {
                    var node = _symbolGraph[asset.Currency];
                    res += (node != null && !searchResult.Distance[node.Id].E(_pathLogic.UnreachableValue))
                        ? asset.Volume * Math.Exp(-searchResult.Distance[node.Id])
                        : double.NaN;
                }
            }

            Output[0] = res;
        }
示例#14
0
        //event handler for calculate path button
        void btnFinalTree_Click(object sender, RoutedEventArgs e)
        {
            if (floorBacklog == null || floorBacklog.Edges == null || floorBacklog.Source == null)
            {
                return;
            }

            //call bellmanFord Function with the list of all edges and initial point
            BellmanFord.MakeBellmanFordTree(floorBacklog.Edges, floorBacklog.Source);


            Tile vertex = floorBacklog.Destination;


            //start from destination and until source is not reached color all the vertices in the way orange (using converting tile into destination as shortcut to painting orange, as destination tiles already have a style, containing orange foreground
            while (vertex.Parent != null)
            {
                vertex.Type = ShapeType.Destination;
                vertex      = vertex.Parent;
            }
        }
示例#15
0
        public override IEnumerable <object> Solve(TextReader inputStream)
        {
            var nm         = inputStream.ReadIntArray();
            var nodesCount = nm[0];
            var edgesCount = nm[1];

            var bellmanFord = new BellmanFord <BasicNode, WeightedEdge>(Enumerable.Repeat(0, edgesCount)
                                                                        .Select(_ => LoadEdge(inputStream.ReadIntArray())), nodesCount);
            var result             = bellmanFord.GetDistancesFrom(new BasicNode(0));
            var distances          = result.Item1;
            var negativeCycleNodes = result.Item2;

            if (negativeCycleNodes[nodesCount - 1])
            {
                yield return("inf");
            }
            else
            {
                yield return(-distances[nodesCount - 1]);
            }
        }
示例#16
0
        private void RunAlgorithm(string _algoName, Graph _graph)
        {
            // Variables
            DateTime  beginning;
            DateTime  end;
            TimeSpan  duration;
            Algorithm algo = null;

            // Création de l’algorithme
            switch (_algoName)
            {
            case "Depth-First":
                algo = new DepthFirst(_graph, this);
                break;

            case "Breadth-First":
                algo = new BreadthFirst(_graph, this);
                break;

            case "Bellman-Ford":
                algo = new BellmanFord(_graph, this);
                break;

            case "Dijkstra":
                algo = new Dijkstra(_graph, this);
                break;

            case "A*":
                algo = new AStar(_graph, this);
                break;
            }
            // Résolution
            Console.Out.WriteLine("Algorithme : " + _algoName);
            beginning = DateTime.Now;
            algo.Solve();
            end      = DateTime.Now;
            duration = end - beginning;
            Console.Out.WriteLine("Durée (ms) : " +
                                  duration.TotalMilliseconds.ToString() + "\n");
        }
示例#17
0
            public void Solve()
            {
                //ABC061 D
                int N = NextInt(), M = NextInt();
                var bf = new BellmanFord(N);

                M.REP(i => {
                    int ai = NextInt() - 1, bi = NextInt() - 1, ci = NextInt();
                    bf.Add(ai, bi, -ci);
                });
                bf.Run(0);

                if (bf.HasCycle)
                {
                    "inf".WL();
                }
                else
                {
                    (-bf.Distance[N - 1]).WL();
                }
                return;
            }
示例#18
0
        public void GetPath_ExistPath_Path()
        {
            var bellmanFord = new BellmanFord("TestPaths.txt");

            bellmanFord.GetPath("Vladivostok", "Moscow");

            var coasts = new List <int>
            {
                13,
                35
            };

            var citiesName = new List <string>
            {
                "Vladivostok",
                "Moscow"
            };

            var expected = (citiesName, coasts);

            var path = (bellmanFord.pathByCities, bellmanFord.pathByPrice);

            Assert.IsTrue(AreEqual(path, expected));
        }
示例#19
0
        public static void BookExampleTestcase()
        {
            // 1. Create a graph
            CGraph mgraph = CGraph.CreateGraph();

            CGraphNode x = mgraph.CreateGraphNode <CGraphNode>("x");
            CGraphNode y = mgraph.CreateGraphNode <CGraphNode>("y");
            CGraphNode z = mgraph.CreateGraphNode <CGraphNode>("z");
            CGraphNode t = mgraph.CreateGraphNode <CGraphNode>("t");
            CGraphNode s = mgraph.CreateGraphNode <CGraphNode>("s");

            mgraph.AddGraphEdge <CGraphEdge, CGraphNode>(t, x, GraphType.GT_DIRECTED);
            mgraph.AddGraphEdge <CGraphEdge, CGraphNode>(t, y, GraphType.GT_DIRECTED);
            mgraph.AddGraphEdge <CGraphEdge, CGraphNode>(t, z, GraphType.GT_DIRECTED);
            mgraph.AddGraphEdge <CGraphEdge, CGraphNode>(x, t, GraphType.GT_DIRECTED);
            mgraph.AddGraphEdge <CGraphEdge, CGraphNode>(y, x, GraphType.GT_DIRECTED);
            mgraph.AddGraphEdge <CGraphEdge, CGraphNode>(y, z, GraphType.GT_DIRECTED);
            mgraph.AddGraphEdge <CGraphEdge, CGraphNode>(z, x, GraphType.GT_DIRECTED);
            mgraph.AddGraphEdge <CGraphEdge, CGraphNode>(z, s, GraphType.GT_DIRECTED);
            mgraph.AddGraphEdge <CGraphEdge, CGraphNode>(s, t, GraphType.GT_DIRECTED);
            mgraph.AddGraphEdge <CGraphEdge, CGraphNode>(s, y, GraphType.GT_DIRECTED);

            // 2. Associate weights with the edges of the graph
            CGraphQueryInfo <int, int, int> weights = new CGraphQueryInfo <int, int, int>(mgraph, 255);

            weights.CreateInfo(y, x, -3);
            weights.CreateInfo(x, t, -2);
            weights.CreateInfo(t, x, 5);
            weights.CreateInfo(z, x, 7);
            weights.CreateInfo(y, z, 9);
            weights.CreateInfo(t, y, 8);
            weights.CreateInfo(t, z, -4);
            weights.CreateInfo(s, t, 6);
            weights.CreateInfo(s, y, 7);
            weights.CreateInfo(z, s, 2);

            // 3. Run the BellmanFord algorithm
            BellmanFord bl = new BellmanFord(mgraph, s, 255);

            bl.FindAllPairsShortestPaths();

            // 4. Print Paths
            CGraphQueryInfo <int, int, Dictionary <CGraphNode, Dictionary <CGraphNode, Path> > > shortestPath = new CGraphQueryInfo <int, int, Dictionary <CGraphNode, Dictionary <CGraphNode, Path> > >(mgraph, bl);
            CIt_GraphNodes i = new CIt_GraphNodes(mgraph);
            CIt_GraphNodes j = new CIt_GraphNodes(mgraph);
            Dictionary <CGraphNode, Dictionary <CGraphNode, Path> > paths =
                (Dictionary <CGraphNode, Dictionary <CGraphNode, Path> >)(shortestPath.Info());

            for (i.Begin(); !i.End(); i.Next())
            {
                Console.WriteLine();
                for (j.Begin(); !j.End(); j.Next())
                {
                    Console.WriteLine();
                    if (i.M_CurrentItem != j.M_CurrentItem)
                    {
                        Console.Write(paths[i.M_CurrentItem][j.M_CurrentItem]);
                    }
                }
            }
        }
示例#20
0
        public static void TestCase3x3()
        {
            // 1. Create a graph
            CGraph mgraph = CGraph.CreateGraph();

            CGraphNode x1 = mgraph.CreateGraphNode <CGraphNode>("1");
            CGraphNode x2 = mgraph.CreateGraphNode <CGraphNode>("2");
            CGraphNode x3 = mgraph.CreateGraphNode <CGraphNode>("3");
            CGraphNode x4 = mgraph.CreateGraphNode <CGraphNode>("4");
            CGraphNode x5 = mgraph.CreateGraphNode <CGraphNode>("5");
            CGraphNode x6 = mgraph.CreateGraphNode <CGraphNode>("6");
            CGraphNode x7 = mgraph.CreateGraphNode <CGraphNode>("7");
            CGraphNode x8 = mgraph.CreateGraphNode <CGraphNode>("8");
            CGraphNode x9 = mgraph.CreateGraphNode <CGraphNode>("9");

            mgraph.AddGraphEdge <CGraphEdge, CGraphNode>(x1, x2, GraphType.GT_DIRECTED);
            mgraph.AddGraphEdge <CGraphEdge, CGraphNode>(x2, x1, GraphType.GT_DIRECTED);
            mgraph.AddGraphEdge <CGraphEdge, CGraphNode>(x1, x5, GraphType.GT_DIRECTED);
            mgraph.AddGraphEdge <CGraphEdge, CGraphNode>(x5, x1, GraphType.GT_DIRECTED);
            mgraph.AddGraphEdge <CGraphEdge, CGraphNode>(x1, x4, GraphType.GT_DIRECTED);
            mgraph.AddGraphEdge <CGraphEdge, CGraphNode>(x4, x1, GraphType.GT_DIRECTED);
            mgraph.AddGraphEdge <CGraphEdge, CGraphNode>(x2, x4, GraphType.GT_DIRECTED);
            mgraph.AddGraphEdge <CGraphEdge, CGraphNode>(x4, x2, GraphType.GT_DIRECTED);
            mgraph.AddGraphEdge <CGraphEdge, CGraphNode>(x2, x3, GraphType.GT_DIRECTED);
            mgraph.AddGraphEdge <CGraphEdge, CGraphNode>(x3, x2, GraphType.GT_DIRECTED);
            mgraph.AddGraphEdge <CGraphEdge, CGraphNode>(x2, x6, GraphType.GT_DIRECTED);
            mgraph.AddGraphEdge <CGraphEdge, CGraphNode>(x6, x2, GraphType.GT_DIRECTED);
            mgraph.AddGraphEdge <CGraphEdge, CGraphNode>(x2, x5, GraphType.GT_DIRECTED);
            mgraph.AddGraphEdge <CGraphEdge, CGraphNode>(x5, x2, GraphType.GT_DIRECTED);
            mgraph.AddGraphEdge <CGraphEdge, CGraphNode>(x3, x5, GraphType.GT_DIRECTED);
            mgraph.AddGraphEdge <CGraphEdge, CGraphNode>(x5, x3, GraphType.GT_DIRECTED);
            mgraph.AddGraphEdge <CGraphEdge, CGraphNode>(x3, x6, GraphType.GT_DIRECTED);
            mgraph.AddGraphEdge <CGraphEdge, CGraphNode>(x6, x3, GraphType.GT_DIRECTED);
            mgraph.AddGraphEdge <CGraphEdge, CGraphNode>(x4, x5, GraphType.GT_DIRECTED);
            mgraph.AddGraphEdge <CGraphEdge, CGraphNode>(x5, x4, GraphType.GT_DIRECTED);
            mgraph.AddGraphEdge <CGraphEdge, CGraphNode>(x4, x7, GraphType.GT_DIRECTED);
            mgraph.AddGraphEdge <CGraphEdge, CGraphNode>(x7, x4, GraphType.GT_DIRECTED);
            mgraph.AddGraphEdge <CGraphEdge, CGraphNode>(x4, x8, GraphType.GT_DIRECTED);
            mgraph.AddGraphEdge <CGraphEdge, CGraphNode>(x8, x4, GraphType.GT_DIRECTED);
            mgraph.AddGraphEdge <CGraphEdge, CGraphNode>(x5, x6, GraphType.GT_DIRECTED);
            mgraph.AddGraphEdge <CGraphEdge, CGraphNode>(x6, x5, GraphType.GT_DIRECTED);
            mgraph.AddGraphEdge <CGraphEdge, CGraphNode>(x5, x7, GraphType.GT_DIRECTED);
            mgraph.AddGraphEdge <CGraphEdge, CGraphNode>(x7, x5, GraphType.GT_DIRECTED);
            mgraph.AddGraphEdge <CGraphEdge, CGraphNode>(x5, x8, GraphType.GT_DIRECTED);
            mgraph.AddGraphEdge <CGraphEdge, CGraphNode>(x8, x5, GraphType.GT_DIRECTED);
            mgraph.AddGraphEdge <CGraphEdge, CGraphNode>(x5, x9, GraphType.GT_DIRECTED);
            mgraph.AddGraphEdge <CGraphEdge, CGraphNode>(x9, x5, GraphType.GT_DIRECTED);
            mgraph.AddGraphEdge <CGraphEdge, CGraphNode>(x6, x8, GraphType.GT_DIRECTED);
            mgraph.AddGraphEdge <CGraphEdge, CGraphNode>(x8, x6, GraphType.GT_DIRECTED);
            mgraph.AddGraphEdge <CGraphEdge, CGraphNode>(x6, x9, GraphType.GT_DIRECTED);
            mgraph.AddGraphEdge <CGraphEdge, CGraphNode>(x9, x6, GraphType.GT_DIRECTED);
            mgraph.AddGraphEdge <CGraphEdge, CGraphNode>(x7, x8, GraphType.GT_DIRECTED);
            mgraph.AddGraphEdge <CGraphEdge, CGraphNode>(x8, x7, GraphType.GT_DIRECTED);
            mgraph.AddGraphEdge <CGraphEdge, CGraphNode>(x8, x9, GraphType.GT_DIRECTED);
            mgraph.AddGraphEdge <CGraphEdge, CGraphNode>(x9, x8, GraphType.GT_DIRECTED);


            // 2. Associate weights with the edges of the graph
            CGraphQueryInfo <int, int, int> weights = new CGraphQueryInfo <int, int, int>(mgraph, 255);

            weights.CreateInfo(x1, x2, 1);
            weights.CreateInfo(x2, x1, 1);
            weights.CreateInfo(x1, x5, 1);
            weights.CreateInfo(x5, x1, 1);
            weights.CreateInfo(x1, x4, 1);
            weights.CreateInfo(x4, x1, 1);
            weights.CreateInfo(x2, x4, 3);
            weights.CreateInfo(x4, x2, 3);
            weights.CreateInfo(x2, x3, 1);
            weights.CreateInfo(x3, x2, 1);
            weights.CreateInfo(x2, x6, 3);
            weights.CreateInfo(x6, x2, 3);
            weights.CreateInfo(x2, x5, 1);
            weights.CreateInfo(x5, x2, 1);
            weights.CreateInfo(x3, x5, 3);
            weights.CreateInfo(x5, x3, 3);
            weights.CreateInfo(x3, x6, 1);
            weights.CreateInfo(x6, x3, 1);
            weights.CreateInfo(x4, x5, 1);
            weights.CreateInfo(x5, x4, 1);
            weights.CreateInfo(x4, x7, 1);
            weights.CreateInfo(x7, x4, 1);
            weights.CreateInfo(x4, x8, 3);
            weights.CreateInfo(x8, x4, 3);
            weights.CreateInfo(x5, x6, 1);
            weights.CreateInfo(x6, x5, 1);
            weights.CreateInfo(x5, x7, 3);
            weights.CreateInfo(x7, x5, 3);
            weights.CreateInfo(x5, x8, 1);
            weights.CreateInfo(x8, x5, 1);
            weights.CreateInfo(x5, x9, 3);
            weights.CreateInfo(x9, x5, 3);
            weights.CreateInfo(x6, x8, 3);
            weights.CreateInfo(x8, x6, 3);
            weights.CreateInfo(x6, x9, 1);
            weights.CreateInfo(x9, x6, 1);
            weights.CreateInfo(x7, x8, 1);
            weights.CreateInfo(x8, x7, 1);
            weights.CreateInfo(x8, x9, 1);
            weights.CreateInfo(x9, x8, 1);

            // 3. Run the BellmanFord algorithm
            BellmanFord bl = new BellmanFord(mgraph, x1, 255);

            bl.FindAllPairsShortestPaths();

            // 4. Print Paths
            BellmanFordQueryInfo shortestPath = new BellmanFordQueryInfo(mgraph, bl);
            CIt_GraphNodes       i            = new CIt_GraphNodes(mgraph);
            CIt_GraphNodes       j            = new CIt_GraphNodes(mgraph);
            Dictionary <CGraphNode, Dictionary <CGraphNode, Path> > paths =
                shortestPath.ShortestPaths();

            for (i.Begin(); !i.End(); i.Next())
            {
                Console.WriteLine();
                for (j.Begin(); !j.End(); j.Next())
                {
                    Console.WriteLine();
                    if (i.M_CurrentItem != j.M_CurrentItem)
                    {
                        Console.Write(paths[i.M_CurrentItem][j.M_CurrentItem]);
                    }
                }
            }
        }
示例#21
0
        static void Main(string[] args)
        {
            // StringProblems
            //Test calls for Reverse string
            string input = "jacob";

            Console.WriteLine(input + "<=>" + new string(SimpleProblem.ReverseString(input.ToCharArray())));
            input = "jake";
            Console.WriteLine(input + "<=>" + new string(SimpleProblem.ReverseString(input.ToCharArray())));
            input = "";
            Console.WriteLine(input + "<=>" + new string(SimpleProblem.ReverseString(input.ToCharArray())));
            input = "jdshjdh@#$%^&)";
            Console.WriteLine(input + "<=>" + new string(SimpleProblem.ReverseString(input.ToCharArray())));

            ReplaceSpaces.TestReplaceSpacesInplace();
            Anagrams.TestIsAnagramAlgo();
            StringRotation.TestIsThisRotatedString();
            RemoveDuplicates.TestRemoveDuplicatesFromString();
            StringToLongConverter.TestStringToLong();
            RegexMatching.TestMatch();
            SumOfTwoNumbersInArray.TestSumOfTwoNumbersInArray();
            SumOfThreeNumbersInArray.TestSumOfThreeNumbersInArray();
            PairInSortedArrayClosestToAParticularValue.TestPairInSortedArrayClosestToAParticularValue();
            PalindromeInStringPermutation.TestPalindromeInStringPermutation();
            EditDistanceBetweenStrings.TestEditDistanceBetweenStrings();
            AnagramIsPalindrome.TestAnagramIsPalindrome();
            GreatestPalindrome.TestGreatestPalindrome();
            ReverseStringWithoutVowels.TestReverseStringWithoutVowels();
            LongestSubstringWithKDistinctChars.TestLongestSubstringWithKDistinctChars();
            // Pattern Matching
            NativePatternMatching.TestNativePatternMatching();
            KMPPatternMatching.TestKMPPatternMatching();
            BoyerMoorePatternMatching.TestPatternMatching();
            RabinKarp.TestRabinKarp();

            //Console.ReadLine();

            //Array Problems
            ArrayOfNumsIncrement.TestIncrementArrayOfNumbers();
            MajorityElement.TestFindMajorityElement();
            Merge2SortedArrays.TestMergeSortedArrays();
            MaxDistanceInArray.TestMaxDistanceInArray();
            MovingAverage.TestMovingAverage();
            TotalAverage.TestTotalAverage();
            ArrayWithGreaterElementToRight.TestArrayWithGreaterElementToRight();
            WaterCollectedInPuddleShownByHistogram.TestWaterCollectedInPuddleShownByHistogram();
            CountOfPairsWhichSumUpToGivenSum.TestCountOfPairsWhichSumUpToGivenSum();
            //Median.TestGetMedianOf2SortedArray();

            // Sorting Problems
            SelectionSort.TestSorting();
            BubbleSort.TestSorting();
            InsertionSort.TestSorting();
            ShellSort.TestSorting();
            MergeSort.TestMergeSort();
            QuickSort.TestQuickSort();
            HeapSortTester.TestHeapSort();
            CountingSort.TestSorting();
            RadixSort.TestRadixSort();
            DutchNationalFlag.TestDutchNationalFlag();
            SortedSquares.TestSortedSquares();

            // Matrix Problem
            Rotate_Matrix_90_degree.TestRotateMatrix();
            Matrix_Column_Rows_0.TestMakeRowColZero1();
            Matrix_Column_Rows_0.TestMakeRowColZero2();
            RotateMatrix180.TestRotateMatrix180();
            SumOfMatrixElementsFormedByRectangleWithCoordinates.TestSumOfMatrixElements();
            SortedArrayFromSortedMatrix.TestSortedArrayFromSortedMatrix();
            SearchWordInMatrix.TestSearchWordInMatrix();
            MaxOnesInRow.TestMaxOnesInRow();
            MatrixAsTriangle.TestMatrixAsTriangle();
            MinRangeInMatrix.TestMinRangeInMatrix();
            PrintMatrixAsSnake.TestPrintMatrixAsSnake();
            PrintMatrixInSpiral.TestPrintMatrixInSpiral();
            MaxSqAreaInBinaryMatrix.TestMaxRectAreaInBinaryMatrix();
            TicTacToeWinner.TestTicTacToeWinner();
            WaterfallCreation.TestWaterfallCreation();

            // Linked list Problems
            DeleteLinkedListNode.TestDeleteFirstNode();
            DeleteDuplicatesFromLinkedList.TestDeleteDuplicates();
            NthLastElementOfLinkedList.TestNthLastNodeOfLinkedList();
            DeleteNodeWithDirectReference.TestDeleteNode();
            AddNumbers.TestAddNumbersRepresentedByLinkedList();
            CopyLinkedListWithRandomNode.TestGetCopiedLinkedListWithRandomNode();
            CommonElementInTwoLinkedList.TestCommonElement();
            ReverseAdjacentNodesInLinkedList.TestReverseAdjacentNodes();
            MergeSortedLinkedList.TestMerge();
            CycleInLinkedList.TestStartOfCycleInLinkedList();
            MedianForCircularLinkedList.TestGetMedian();
            ReverseLinkedList.TestReverseLinkedList();
            SortedCircularLinkedList.TestCircularLinkedList();

            // stack and queue problem
            ThreeStackWithOneArray.TestThreeStackWithOneArray();
            StackWithMinElement.TestStackWithMinElement();
            StackOfPlates.TestStackOfPlates();
            SortAStack.TestSortAStackAscending();
            WellFormedExpression.TestWellFormedExpression();
            QueueVia2Stack.TestQueueVia2Stack();
            LRUCache.TestLRUCache();
            EvaluatePrefixNotation.TestGetPrefixNotationResult();
            EvaluateInflixNotation.TestGetInflixNotationResults();
            EvaluatePostfixNotation.TestGetPostfixNotationResult();
            TestCircularQueue.TestCircularQueueWithDifferentCases();
            LargestAreaInHistogram.TestLargestAreaInHistogram();
            TextEditerWithUndo.TestTextEditerWithUndo();

            //Recursion Problem
            TowerOfHanoi.TestTowerOfHanoi();
            MaxSumOfConsecutiveNums.TestMaxSumOfConsecutiveNums();

            // Back tracking problems
            Sudoku.TestSudokuSolver();
            HamiltonianCycle.TestHamiltonianCycle();
            GraphColoringWithMColors.TestGraphColoringWithMColors();
            MakeLargestIsland.TestMakeLargestIsland();

            //Misc Problem
            MinNumOfCoins.TestMinNumOfCoins();
            IsPrime.TestCheckPrime();
            SquareRoot.TestCalculateSquareRoot();
            CreditCardCheck.TestLuhnAlgo();
            ExcelFirstRowConversion.TestCovertExcelColumnToLong();
            Skyline.TestSkyline();
            SumOfSquaresWithoutMultiplication.TestSumOfSquares();
            MergeIntervals.TestMergeIntervals();
            WidthOfCalendar.TestWidthOfCalendar();
            JosephusProblem.TestJosephusProblem();

            // Permutation and Combination problem
            ShuffleAList.TestFisherYatesAlgo();
            CombinationsOfBinaryString.TestCombinationsOfBinaryString();
            AllCombinationsOfString.TestAllCombinationsOfString();
            AllPermutationsOfString.TestAllPermutationsOfString();
            PhoneNumberToWords.TestPhoneNumberToWords();
            AllNumbersInRangeWithDifferentDigits.TestAllNumbersInRangeWithDifferentDigits();
            DivideSetIntoTwoEqualSetsWithMinSumDiff.TestDivideSetIntoTwoEqualSetsWithMinSumDiff();
            PowerSet.TestPowerSet();
            AllCombinationsOfParenthesis.TestAllCombinationsOfParenthesis();
            GoodDiceRoll.TestGoodDiceRoll();
            PermutationsOfValidTime.TestPermutationsOfValidTime();

            // Tree Problems
            TreeFromExpression.TestCreateTreeFromExpression();
            TestBinarySearchTree.TestDifferentOperationsOnBST();
            AncestorOfTwoNodesInBST.TestAncestorOfTwoNodesInBST();
            CheckBTisBST.TestCheckBTisBST();
            MaxSumOnTreeBranch.TestMaxSum();
            WalkTheTree.TestWalkTheTree();
            SkewedBSTToCompleteBST.TestConvertSkewedBSTToCompleteBST();
            CheckIfTheTreeIsBalanced.TestIsTreeBalanced();
            LinkedListOfTreeNodesAtEachDepth.TestCreateLinkedListOfTreeNodesAtEachDepth();
            PrintBinaryTreeNodeAtEachLevel.TestPrintBinaryTreeNodeAtEachLevel();
            PrintBinaryTreeNodeAtEachLevelSpirally.TestPrintBinaryTreeNodeAtEachLevelSpirally();
            TreeSubtreeOfAnother.TestMatchTree();
            AncestorOfTwoNodesInBT.TestGetAncestorOfTwoNodesInBT();
            AncestorOfMultiNodesInBT.TestAncestorOfMultiNodesInBT();
            LinkedListFromLeavesOfBT.TestLinkedListFromLeavesOfBT();
            ExteriorOfBT.TestPrintExteriorOfBT();
            DepthOfTree.TestGetDepthOfTree();
            TreeToColumns.TestTreeToColumns();
            KthSmallestElementFromBST.TestKthSmallestElementFromBST();
            MakeBSTFromPreOrder.TestMakeBSTFromPreOrder();
            MirrorATree.TestMirrorATree();
            CloneABTWithRandPointer.TestCloneABTWithRandPointer();
            TreeWithInorderAndPreorder.TestTreeWithInorderAndPreorder();
            TreeWithInorderAndPostorder.TestTreeWithInorderAndPostorder();
            TreePathSumsToValue.TestTreePathSumsToValue();
            AllPathInNArayTree.TestAllPathInNArayTree();
            SerializeDeserializeBinaryTree.TestSerializeDeserializeBinaryTree();
            SerializeDeserializeAnNaryTree.TestSerializeDeserializeAnNaryTree();
            AncestorOfTwoNodesInNaryTree.TestAncestorOfTwoNodesInNaryTree();
            AbsOfMaxAndSecondMaxDepthInBT.TestGetAbsOfMaxAndSecondMaxDepthInBT();

            // Trie problems
            CreateAndSearchSimpleTrie.TestCreateAndSearchSimpleTrie();
            // ToDo: have a problem of suffix trees
            ShortestPrefix.TestGetShortestPrefixNotPresentInStringSet();

            // Dynamic Programming problems
            LongestCommonSubsequence.TestGetLongestCommonSubsequence();
            LongestPalindromeSubString.TestGetLongestPalindromeSubString();
            LongestPalindromicSubsequence.TestGetLongestPalindromicSubsequence();
            MaximumAs.TestGetMaximumAs();
            MinNumberOfJumps.TestGetMinimumNumberOfJumps();
            LongestCommonSubString.TestGetLongestCommonSubString();
            KnapSackProblem.TestGetTheMaximumValueWithLimitedWeight();
            TreeCuttingProblem.TestGetTreeCuttingToMaximizeProfits();
            WordBreaking.TestBreakTheWords();
            DistanceOfWords.TestDistanceOfWords();
            LongestIncreasingSubSequence.TestLongestIncreasingSubSequence();
            MinCostPath.TestMinCostPath();
            DifferentWaysForCoinChange.TestDifferentWaysForCoinChange();
            MatrixMultiplication.TestMatrixMultiplication();
            BinomialCoefficient.TestBinomialCoefficient();
            BoxStacking.TestBoxStacking();
            WordWrapping.TestWordWrapping();
            MaxSubMatrixWithAllOnes.TestMaxSubMatrixWithAllOnes();
            LongestSubStringWithEqualSum.TestLongestSubStringWithEqualSum();
            PartitionArrayIntoEqualSumSets.TestPartitionArrayIntoEqualSumSets();
            MaxSumRectangle.TestMaxSumRectangle();
            RegularExpressionMatch.TestRegularExpressionMatch();
            NumRepresentedByPerfectSquares.TestNumRepresentedByPerfectSquares();
            LongestCommonSubsequenceInSameString.TestLongestCommonSubsequenceInSameString();
            StringDecodeAsAlphabets.TestStringDecodeAsAlphabets();
            BalloonBursting.TestBalloonBursting();
            TravellingSalesmanProblem.TestTravellingSalesmanProblem();
            MaxSumWithoutAdjacentElements.TestMaxSumWithoutAdjacentElements();
            MaxPathThroughMatrix.TestMaxPathThroughMatrix();
            BrickLaying.TestBrickLaying();
            JobSchedullingWithConstraints.TestJobSchedullingWithConstraints();
            EggDropMinTrials.TestEggDropMinTrials();

            // Graph Problems
            ShortestPath.TestGetShortestPathBetween2Vertex();
            CycleInDirectedGraph.TestIsCycleInDirectedGraph();
            CycleInUnDirectedGraph.TestIsCycleInUnDirectedGraph();
            SolveAMaze.TestSolveAMaze();
            AllPathsGivenStartEndVertex.TestGetAllPathsInGraphFromStartVertexToEndVertex();
            AllPaths.TestGetAllPathsInGraphFromStartVertex();
            ColorVertices.TestColorVerticesWithDifferentColor();
            CheckBipartiteGraph.TestCheckBipartiteGraph();
            TransformOneWordToAnother.TestGetTransformation();
            ConstraintsVerification.TestConstraintsVerification();
            ExtendedContactsInSocialNetwork.TestComputeExtendedContacts();
            CourseScheduling.TestCourseScheduling();
            SnakeAndLadder.TestSnakeAndLadder();
            IsGraphATree.TestIsGraphATree();
            ReverseGraph.TestReverseGraph();
            StronglyConnectedGraph.TestStronglyConnectedGraph();
            ConnectedComponents.TestConnectedComponents();
            ContinentalDivide.TestContinentalDivide();
            CloneGraph.TestCloneGraph();
            Wordament.TestWordament();
            // ShortestPathAlgo
            FloydWarshall.TestFloydWarshall();
            DijkstraAlgorithm.TestDijkstraAlgorithm();
            BellmanFord.TestBellmanFord();
            TravelFromLeftToRightInMatrix.TestTravelFromLeftToRightInMatrix();
            HeuristicSearch.TestHeuristicSearch();
            AStar.TestAStar();
            ShortestPathWhenObstaclesRemoved.TestShortestPathWhenObstaclesRemoved();
            ShortestDistanceFromRoomsToGates.TestShortestDistanceFromRoomsToGates();
            //MaxFlow
            FordFulkersonEdmondKarp.TestFordFulkersonEdmondKarp();
            MinCut.TestMinCut();
            MaximumBipartiteMatching.TestMaximumBipartiteMatching();
            //Minimum Spanning Tree
            KruskalAlgorithm.TestKruskalAlgorithm();
            PrimsAlgorithm.TestPrimsAlgorithm();


            //Heap problems
            BasicMaxHeap.TestMaxHeap();
            BasicMinHeap.TestMinHeap();
            TestMinHeapMap.DoTest();
            TestPriorityQueue.Run();
            MedianForAStreamOfNumbers.TestMedianForAStreamOfNumbers();

            //DisjointSets
            TestingDisjointSet.Run();
            //TestWeightedDisjointSetsWithPathCompression.Run(); // this runs slow, hence commenting it

            //Geometry
            ClosestPairOfPoints.TestClosestPairOfPoints();
            RectangleIntersection.TestRectangleIntersection();
            LineSegmentIntersection.TestLineSegmentIntersection();
            ConvexHull.TestConvexHull();
            KClosestPointToOrigin.TestKClosestPointToOrigin();

            //Greedy Algorithm
            HuffmanCoding.TestHuffmanCoding();

            //Randomized Algorithm
            RandomGeneration.TestRandomGeneration();

            // Bit Algorithms
            IntHaveOppositeSigns.TestIntHaveOppositeSigns();
            Parity.TestParity();

            //Math Problem
            ZerosInFactorial.TestZerosInFactorial();
            GetAllPrimeFactors.TestGetAllPrimeFactors();
            NumberOfFactors.TestNumberOfFactors();
            AllFactors.TestAllFactors();
            MultiplyLongNumbers.TestMultiplyLongNumbers();
            NextLargestPermutation.TestNextLargestPermutation();
            AllPrimesTillN.TestAllPrimesTillN();
            PascalsTriangle.TestPascalsTriangle();
            SubtractLongNumbers.TestSubtractLongNumbers();

            //Search problems
            SearchInSortedRotatedArray.TestSearchInSortedRotatedArray();
            KClosestElementInArray.TestKClosestElementInArray();
            SearchInSortedMatrix.TestSearchInSortedMatrix();
            BinarySearchUnbounded.TestBinarySearchUnbounded();
            LinkedListSublistSearch.TestLinkedListSublistSearch();
            NoOfOccuranceInSortedArray.TestNoOfOccuranceInSortedArray();
            GetSmallestInSortedRotatedArray.TestGetSmallestInSortedRotatedArray();

            //Distributed algorithms
            KWayMerge.TestKWayMerge();


            Console.ReadLine();
        }
示例#22
0
    private static void test01()

    //****************************************************************************80
    //
    //  Purpose:
    //
    //    TEST01 runs a simple test.
    //
    //  Discussion:
    //
    //    The correct distances are { 0, -6, -2, 3, 0, 0 }.
    //
    //  Licensing:
    //
    //    This code is distributed under the GNU LGPL license.
    //
    //  Modified:
    //
    //    11 November 2014
    //
    //  Author:
    //
    //    John Burkardt
    //
    {
        int[] e =
        {
            1, 0,
            4, 1,
            1, 2,
            2, 4,
            4, 0,
            2, 5,
            5, 0,
            3, 2,
            5, 3,
            3, 0
        }

        ;
        const int e_num = 10;

        double[] e_weight =
        {
            -3.0,
            6.0,
            -4.0,
            -1.0,
            4.0,
            -2.0,
            2.0,
            8.0,
            -3.0,
            3.0
        }

        ;
        int[]     predecessor = new int[6];
        const int source      = 0;
        const int v_num       = 6;

        double[] v_weight = new double[6];

        Console.WriteLine("");
        Console.WriteLine("TEST01:");
        Console.WriteLine("  Bellman-Ford shortest path algorithm.");

        Console.WriteLine("");
        Console.WriteLine("  Number of vertices = " + v_num + "");
        Console.WriteLine("  Number of edges = " + e_num + "");
        Console.WriteLine("  The reference vertex is " + source + "");
        typeMethods.i4mat_transpose_print(2, e_num, e, "  The edge array:");
        typeMethods.r8vec_print(e_num, e_weight, "  The edge weights:");

        BellmanFord.bellman_ford(v_num, e_num, source, e, e_weight, ref v_weight, ref predecessor);

        typeMethods.r8vec_print(v_num, v_weight, "  The shortest distances:");

        typeMethods.i4vec_print(v_num, predecessor, "  The vertex predecessor parents for the shortest paths:");
    }
示例#23
0
        private void Run()
        {
            // 1st map
            String mapStr = "..  XX   .\n"
                            + "*.  *X  *.\n"
                            + " .  XX ...\n"
                            + " .* X *.* \n"
                            + " ...=...  \n"
                            + " .* X     \n"
                            + " .  XXX*  \n"
                            + " .  * =   \n"
                            + " .... XX  \n"
                            + "   *.  X* ";
            Map       map  = new Map(mapStr, 0, 0, 9, 9);
            Algorithm algo = new DepthFirst(map, this);

            algo.Solve();
            Console.WriteLine();
            algo = new BreadthFirst(map, this);
            algo.Solve();
            Console.WriteLine();
            algo = new BellmanFord(map, this);
            algo.Solve();
            Console.WriteLine();
            algo = new Dijkstra(map, this);
            algo.Solve();
            Console.WriteLine();
            algo = new AStar(map, this);
            algo.Solve();
            Console.WriteLine();

            // 2nd map
            mapStr = "...*     X .*    *  \n"
                     + " *..*   *X .........\n"
                     + "   .     =   *.*  *.\n"
                     + "  *.   * XXXX .    .\n"
                     + "XXX=XX   X *XX=XXX*.\n"
                     + "  *.*X   =  X*.  X  \n"
                     + "   . X * X  X . *X* \n"
                     + "*  .*XX=XX *X . XXXX\n"
                     + " ....  .... X . X   \n"
                     + " . *....* . X*. = * ";
            map  = new Map(mapStr, 0, 0, 9, 19);
            algo = new DepthFirst(map, this);
            algo.Solve();
            Console.WriteLine();
            algo = new BreadthFirst(map, this);
            algo.Solve();
            Console.WriteLine();
            algo = new BellmanFord(map, this);
            algo.Solve();
            Console.WriteLine();
            algo = new Dijkstra(map, this);
            algo.Solve();
            Console.WriteLine();
            algo = new AStar(map, this);
            algo.Solve();
            Console.WriteLine();

            Console.ReadKey();
        }
示例#24
0
        public void UnitGraphInMatrix()
        {
            BellmanFord newShortPath = new BellmanFord();

            newShortPath.Nodes        = new List <Node>();
            newShortPath.Edges        = new List <Edge>();
            newShortPath.PosNodeStart = 0;
            newShortPath.MaxValue     = -1;

            for (int i = 0; i < 5; i++)
            {
                Node a = new Node();
                a.Value = i;
                newShortPath.Nodes.Add(a);
            }

            newShortPath.Edges.Add(new Edge()
            {
                A = newShortPath.Nodes[0], B = newShortPath.Nodes[1], Weight = 6
            });
            newShortPath.Edges.Add(new Edge()
            {
                A = newShortPath.Nodes[0], B = newShortPath.Nodes[3], Weight = 7
            });

            newShortPath.Edges.Add(new Edge()
            {
                A = newShortPath.Nodes[1], B = newShortPath.Nodes[2], Weight = 5
            });
            newShortPath.Edges.Add(new Edge()
            {
                A = newShortPath.Nodes[1], B = newShortPath.Nodes[3], Weight = 8
            });
            newShortPath.Edges.Add(new Edge()
            {
                A = newShortPath.Nodes[1], B = newShortPath.Nodes[4], Weight = -4
            });

            newShortPath.Edges.Add(new Edge()
            {
                A = newShortPath.Nodes[2], B = newShortPath.Nodes[0], Weight = -2
            });

            newShortPath.Edges.Add(new Edge()
            {
                A = newShortPath.Nodes[4], B = newShortPath.Nodes[2], Weight = 7
            });
            newShortPath.Edges.Add(new Edge()
            {
                A = newShortPath.Nodes[4], B = newShortPath.Nodes[0], Weight = 2
            });

            newShortPath.Edges.Add(new Edge()
            {
                A = newShortPath.Nodes[3], B = newShortPath.Nodes[4], Weight = 9
            });
            newShortPath.Edges.Add(new Edge()
            {
                A = newShortPath.Nodes[3], B = newShortPath.Nodes[2], Weight = -3
            });

            Console.Error.WriteLine("Graph simple sens");
            //graph simple sens
            int[,] test = newShortPath.GraphInMatrix();

            for (int i = 0; i < test.GetLongLength(0); i++)
            {
                for (int j = 0; j < test.GetLongLength(1); j++)
                {
                    Console.Error.Write(test[i, j]);
                }
                Console.Error.WriteLine();
            }

            Console.Error.WriteLine("Graph double sens");
            //graphe double sens
            int[,] test2 = newShortPath.GraphInMatrixDoubleSens();
            for (int i = 0; i < test2.GetLongLength(0); i++)
            {
                for (int j = 0; j < test2.GetLongLength(1); j++)
                {
                    Console.Error.Write(test2[i, j]);
                }
                Console.Error.WriteLine();
            }
        }
示例#25
0
        public void UnitBellmanFord()
        {
            BellmanFord newShortPath = new BellmanFord();

            newShortPath.Nodes        = new List <Node>();
            newShortPath.Edges        = new List <Edge>();
            newShortPath.PosNodeStart = 0;
            newShortPath.MaxValue     = 9999;
            for (int i = 1; i < 6; i++)
            {
                Node a = new Node();
                //a.Value = 0;
                a.Value = i;
                newShortPath.Nodes.Add(a);
            }

            newShortPath.Edges.Add(new Edge()
            {
                A = newShortPath.Nodes[0], B = newShortPath.Nodes[1], Weight = 6
            });
            newShortPath.Edges.Add(new Edge()
            {
                A = newShortPath.Nodes[0], B = newShortPath.Nodes[3], Weight = 7
            });

            newShortPath.Edges.Add(new Edge()
            {
                A = newShortPath.Nodes[1], B = newShortPath.Nodes[2], Weight = 5
            });
            newShortPath.Edges.Add(new Edge()
            {
                A = newShortPath.Nodes[1], B = newShortPath.Nodes[3], Weight = 8
            });
            newShortPath.Edges.Add(new Edge()
            {
                A = newShortPath.Nodes[1], B = newShortPath.Nodes[4], Weight = -4
            });

            newShortPath.Edges.Add(new Edge()
            {
                A = newShortPath.Nodes[2], B = newShortPath.Nodes[1], Weight = -2
            });

            newShortPath.Edges.Add(new Edge()
            {
                A = newShortPath.Nodes[4], B = newShortPath.Nodes[2], Weight = 7
            });
            newShortPath.Edges.Add(new Edge()
            {
                A = newShortPath.Nodes[4], B = newShortPath.Nodes[0], Weight = 2
            });

            newShortPath.Edges.Add(new Edge()
            {
                A = newShortPath.Nodes[3], B = newShortPath.Nodes[4], Weight = 9
            });
            newShortPath.Edges.Add(new Edge()
            {
                A = newShortPath.Nodes[3], B = newShortPath.Nodes[2], Weight = -3
            });

            string result      = "";
            bool   okNoCyleNeg = newShortPath.BellmanFordWork();

            if (okNoCyleNeg)
            {
                for (int i = 0; i < newShortPath.Nodes.Count; i++)
                {
                    result += newShortPath.Nodes[i].Value;
                    bool ok = true;
                    while (ok)
                    {
                        if (newShortPath.Nodes[i].parent != null)
                        {
                            result += newShortPath.Nodes[i].parent.Value;
                            newShortPath.Nodes[i] = newShortPath.Nodes[i].parent;
                        }
                        else
                        {
                            ok = false;
                        }
                    }
                }
            }
            Assert.AreEqual("0247047070-22470", result);
        }
示例#26
0
        public void GetPath_BadInputData_Exception()
        {
            BellmanFord bellmanFord = new BellmanFord("TestPath.txt");

            Assert.Throws <Exception>(() => bellmanFord.GetPath("Abooba", "Khabarovsk"));
        }
示例#27
0
        public void GetPath_BadFileData_Exception()
        {
            BellmanFord bellmanFord = new BellmanFord("IncorrectInput.txt");

            Assert.Throws <Exception>(() => bellmanFord.GetPath("Khabarovsk", "St. Petersburg"));
        }
示例#28
0
        public void GetPath_NoExistPath_Exception()
        {
            BellmanFord bellmanFord = new BellmanFord("TestPath.txt");

            Assert.Throws <Exception>(() => bellmanFord.GetPath("Khabarovsk", "St. Petersburg"));
        }
示例#29
0
        static void Main(string[] args)
        {
            var djSet = new DisjointSet();
            var edgesForDisjoinSet = new int[8][]
            {
                new int[] { 1, 2 },
                new int[] { 2, 3 },
                new int[] { 4, 5 },
                new int[] { 6, 7 },
                new int[] { 5, 6 },
                new int[] { 3, 7 },
                new int[] { 3, 4 },
                new int[] { 1, 6 }
            };

            //foreach (var edge in edgesForDisjoinSet)
            //{
            //    var result = djSet.AddEdge(edge[0],edge[1]);
            //}

            var edgesForKruskal = new List <IEdgeWithWeight>()
            {
                new EdgeWithWeight {
                    FromNode = 1, ToNode = 2, Weight = 3
                },
                new EdgeWithWeight {
                    FromNode = 1, ToNode = 4, Weight = 1
                },
                new EdgeWithWeight {
                    FromNode = 2, ToNode = 3, Weight = 1
                },
                new EdgeWithWeight {
                    FromNode = 2, ToNode = 4, Weight = 3
                },
                new EdgeWithWeight {
                    FromNode = 3, ToNode = 4, Weight = 1
                },
                new EdgeWithWeight {
                    FromNode = 3, ToNode = 5, Weight = 5
                },
                new EdgeWithWeight {
                    FromNode = 3, ToNode = 6, Weight = 4
                },
                new EdgeWithWeight {
                    FromNode = 4, ToNode = 5, Weight = 6
                },
                new EdgeWithWeight {
                    FromNode = 5, ToNode = 6, Weight = 2
                },
            };

            //var kruskalAlgo = new KruskalAlgo(edgesForKruskal);
            //var minSpanTreeEdges = kruskalAlgo.GetMinSpanningTree();
            //var edgeSum = minSpanTreeEdges.Sum(x => x.Weight);

            var edgesForTopSort = new List <IEdge>()
            {
                new Edge {
                    FromNode = 5, ToNode = 0
                },
                new Edge {
                    FromNode = 5, ToNode = 2
                },
                new Edge {
                    FromNode = 0, ToNode = 2
                },
                new Edge {
                    FromNode = 0, ToNode = 3
                },
                new Edge {
                    FromNode = 3, ToNode = 1
                },
                new Edge {
                    FromNode = 4, ToNode = 1
                },
                new Edge {
                    FromNode = 4, ToNode = 2
                },
            };

            //var topSort = new TopologicalSort(edgesForTopSort);
            //var resultFromTopSort = topSort.GetToplogicalSort();

            var edgesForDijkstra = new List <IEdgeWithWeight>
            {
                new EdgeWithWeight {
                    FromNode = 0, ToNode = 1, Weight = 1
                },
                new EdgeWithWeight {
                    FromNode = 1, ToNode = 0, Weight = 1
                },
                new EdgeWithWeight {
                    FromNode = 0, ToNode = 2, Weight = 4
                },
                new EdgeWithWeight {
                    FromNode = 2, ToNode = 0, Weight = 4
                },
                new EdgeWithWeight {
                    FromNode = 1, ToNode = 2, Weight = 4
                },
                new EdgeWithWeight {
                    FromNode = 2, ToNode = 1, Weight = 4
                },
                new EdgeWithWeight {
                    FromNode = 1, ToNode = 3, Weight = 2
                },
                new EdgeWithWeight {
                    FromNode = 3, ToNode = 1, Weight = 2
                },
                new EdgeWithWeight {
                    FromNode = 1, ToNode = 4, Weight = 7
                },
                new EdgeWithWeight {
                    FromNode = 4, ToNode = 1, Weight = 7
                },
                new EdgeWithWeight {
                    FromNode = 2, ToNode = 3, Weight = 3
                },
                new EdgeWithWeight {
                    FromNode = 3, ToNode = 2, Weight = 3
                },
                new EdgeWithWeight {
                    FromNode = 2, ToNode = 4, Weight = 5
                },
                new EdgeWithWeight {
                    FromNode = 4, ToNode = 2, Weight = 5
                },
                new EdgeWithWeight {
                    FromNode = 3, ToNode = 4, Weight = 4
                },
                new EdgeWithWeight {
                    FromNode = 4, ToNode = 3, Weight = 4
                },
                new EdgeWithWeight {
                    FromNode = 3, ToNode = 5, Weight = 6
                },
                new EdgeWithWeight {
                    FromNode = 5, ToNode = 3, Weight = 6
                },
                new EdgeWithWeight {
                    FromNode = 4, ToNode = 5, Weight = 7
                },
                new EdgeWithWeight {
                    FromNode = 5, ToNode = 4, Weight = 7
                }
            };

            var dijkstra = new Dijkstra(edgesForDijkstra, 0);
            //var resultFromDijkstra = dijkstra.GetMinPath();

            var bellmanFord = new BellmanFord(edgesForDijkstra, 0);
            //var resultFromBellmanFord = bellmanFord.GetMinPath();


            var edgesForTarjansSCC = new List <IEdge>
            {
                new Edge {
                    FromNode = 0, ToNode = 1
                },
                new Edge {
                    FromNode = 0, ToNode = 2
                },
                new Edge {
                    FromNode = 1, ToNode = 3
                },
                new Edge {
                    FromNode = 3, ToNode = 4
                },
                new Edge {
                    FromNode = 4, ToNode = 5
                },
                new Edge {
                    FromNode = 5, ToNode = 2
                },
                new Edge {
                    FromNode = 2, ToNode = 1
                },
                //new Edge {FromNode = 5, ToNode = 0},
            };
            var tarjans = new TarjansAlgo(edgesForTarjansSCC);
            var scc     = tarjans.GetStronglyConnectedComponents();


            var edgesForTarjansBridges = new List <IEdge>
            {
                new Edge {
                    FromNode = 0, ToNode = 1
                },
                new Edge {
                    FromNode = 1, ToNode = 0
                },
                new Edge {
                    FromNode = 0, ToNode = 2
                },
                new Edge {
                    FromNode = 2, ToNode = 0
                },
                new Edge {
                    FromNode = 1, ToNode = 2
                },
                new Edge {
                    FromNode = 2, ToNode = 1
                },
                new Edge {
                    FromNode = 2, ToNode = 3
                },
                new Edge {
                    FromNode = 3, ToNode = 2
                },
                new Edge {
                    FromNode = 3, ToNode = 4
                },
                new Edge {
                    FromNode = 4, ToNode = 3
                },
                new Edge {
                    FromNode = 4, ToNode = 5
                },
                new Edge {
                    FromNode = 5, ToNode = 4
                },
                new Edge {
                    FromNode = 5, ToNode = 6
                },
                new Edge {
                    FromNode = 6, ToNode = 5
                },
                new Edge {
                    FromNode = 4, ToNode = 6
                },
                new Edge {
                    FromNode = 6, ToNode = 4
                },
                new Edge {
                    FromNode = 5, ToNode = 7
                },
                new Edge {
                    FromNode = 7, ToNode = 5
                },
                //new Edge {FromNode = 5, ToNode = 0},
            };

            tarjans = new TarjansAlgo(edgesForTarjansBridges);
            var bridges = tarjans.GetBridgesAndArticulationPoints();
        }
示例#30
0
 private static bool[] RunBellmanFord(Vertex[] vertices, int source)
 {
     BellmanFord.Run(vertices, source);
     return(vertices.Select(v => v.Depth != int.MaxValue).ToArray());
 }