コード例 #1
0
        static void GraphMethod()
        {
            Graph <string> graph = new Graph <string>();

            var nd = graph.AddNode("North Dakota");
            var mt = graph.AddNode("Montana");
            var ga = graph.AddNode("Georgia");
            var ca = graph.AddNode("California");
            var wa = graph.AddNode("Washington");

            graph.AddDirectedEdge(wa, nd, 125);
            graph.AddUndirectedEdge(ca, mt, 100);
            graph.AddDirectedEdge(ga, mt, 72);
            graph.AddUndirectedEdge(wa, ca, 11);
            graph.AddDirectedEdge(nd, mt, 7);

            graph.Print();

            var neighbors = graph.GetNeighbors(wa);

            var getAll = graph.GetAllVertices();
        }
コード例 #2
0
        static void GraphExample()
        {
            Graph <string> graph = new Graph <string>();

            Vertex <string> a = graph.AddNode("Washington");
            Vertex <string> b = graph.AddNode("Montana");
            Vertex <string> c = graph.AddNode("North Dakota");


            graph.AddUnDirectedEdge(a, b, 10);
            graph.AddUnDirectedEdge(b, c, 5);
            graph.AddUnDirectedEdge(c, a, 20);


            graph.Print();

            Console.WriteLine("=== Just Washington ====");

            var vertex    = graph.GetVertex("Washington");
            var neighbors = graph.GetNeighbors(vertex);

            Console.Write($"{vertex.Value}:");

            foreach (var item in neighbors)
            {
                Console.Write($"{item.Vertex.Value}, {item.Weight} => ");
            }


            Console.WriteLine($"Our Graph has {graph.Size()} vertices");
            var listOfVer = graph.GetAllVertices();
            int count     = 0;

            foreach (var item in listOfVer)
            {
                count++;
                Console.WriteLine($"{count}){item.Value}");
            }
        }
コード例 #3
0
        static void Main(string[] args)
        {
            Graph <int> graph = new Graph <int>();

            graph.AddNode(1);
            graph.AddNode(2);
            graph.AddNode(3);
            graph.AddNode(4);
            graph.AddNode(5);

            graph.AddEdge(1, 2);
            graph.AddEdge(1, 3);
            graph.AddEdge(1, 4);
            graph.AddEdge(2, 3);
            graph.AddEdge(2, 5);
            graph.AddEdge(3, 5);
            graph.AddEdge(3, 4);
            graph.AddEdge(4, 5);

            Console.WriteLine(string.Join(", ", graph.GetNodes()));
            Console.WriteLine(string.Join(", ", graph.BreadthFirst(2)));
        }
コード例 #4
0
        /// <summary>
        /// Test clearing a graph
        /// </summary>
        static void TestClear()
        {
            Graph <int> graph = new Graph <int>();

            graph.AddNode(4);
            graph.AddNode(5);
            graph.AddEdge(4, 5);
            graph.Clear();
            Console.Write("TestClear: ");
            string graphString = graph.ToString();

            if (graphString.Equals("") &&
                graph.Count == 0)
            {
                Console.WriteLine("Passed");
            }
            else
            {
                Console.WriteLine("FAILED!!! Expected: empty string" +
                                  " and 0 Actual: " +
                                  graphString + " and " + graph.Count);
            }
        }
コード例 #5
0
        private static void Graph()
        {
            Console.WriteLine("Graph!");
            Console.WriteLine("Add nodes separated by space");

            var nodes = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse);

            var graph = new Graph();

            foreach (var node in nodes)
            {
                graph.AddNode(node);
            }

            var input = "";

            while (input != "quit")
            {
                PrintMenu();

                input = Console.ReadLine();

                if (input.StartsWith("q"))
                {
                    break;
                }

                var split = input.Split(' ');

                var source = int.Parse(split[1]);
                var dest   = int.Parse(split[2]);

                switch (split[0])
                {
                case "edge":
                    graph.AddEdge(source, dest);
                    break;

                case "dfs":
                    var list = graph.HasPathDFS(source, dest);
                    PrintResult("DFS", list);
                    break;

                case "bfs":
                    Console.WriteLine($"BFS Found: [{graph.HasPathBFS(source, dest)}]");
                    break;
                }
            }
        }
コード例 #6
0
        /// <summary>
        /// Test adding an edge to a non-existent node
        /// </summary>
        static void TestAddEdgeNodeNotFound()
        {
            Graph <int> graph = new Graph <int>();

            graph.AddNode(4);
            graph.AddNode(5);
            bool success = graph.AddEdge(4, 6);

            Console.Write("TestAddEdgeNodeNotFound: ");
            string graphString = graph.ToString();

            if (graphString.Equals("[Node Value: 4 Neighbors: ]," + "[Node Value: 5 Neighbors: ]") &&
                !success)
            {
                Console.WriteLine("Passed");
            }
            else
            {
                Console.WriteLine("FAILED!!! Expected: " +
                                  "[Node Value: 4 Neighbors: ]," +
                                  "[Node Value: 5 Neighbors: ] and false Actual: " +
                                  graphString + " and " + success);
            }
        }
コード例 #7
0
        private void AddNode(object sender, MouseButtonEventArgs e)
        {
            if (e.ChangedButton == MouseButton.Right)
            {
                GraphNode node = new GraphNode();
                node.Index = Graph.LastIndex + 1;
                node.IndexLabel.Content = node.Index;

                Canvas.SetLeft(node, e.GetPosition(CanvasGrid).X - node.Width / 2);
                Canvas.SetTop(node, e.GetPosition(CanvasGrid).Y - node.Height / 2);
                CanvasGrid.Children.Add(node);

                Canvas.SetZIndex(node, 1);
                Graph.AddNode(node);
            }
        }
コード例 #8
0
ファイル: NavGraphCreator.cs プロジェクト: senchov/ECS
 public void CreateGraph()
 {
     CreateVisualGraph();
     Graph = new Graph <NavGraphNode, GraphEdge>();
     for (int i = 0; i < Points.Count; i++)
     {
         NodeInfoComponent nodeInfo = Points[i].GetComponent <NodeInfoComponent>();
         Graph.AddNode(new NavGraphNode(nodeInfo.Index, Points[i].transform.position, nodeInfo.ExtraInfo));
         for (int j = 0; j < nodeInfo.ConnectedNodes.Count; j++)
         {
             float distanceBetweenNodes = Vector2.Distance(Points[nodeInfo.Index].transform.position,
                                                           Points[nodeInfo.ConnectedNodes[j]].transform.position);
             Graph.AddEdge(new GraphEdge(nodeInfo.Index, nodeInfo.ConnectedNodes[j], distanceBetweenNodes),
                           nodeInfo.Index);
         }
     }
 }
コード例 #9
0
        /// <summary>
        /// Creates a Connected Cyclic Graph for Testing purposes
        /// </summary>
        public static void PopulateGraph()
        {
            Vertex <int> nodeA = graph.AddNode(5);
            Vertex <int> nodeB = graph.AddNode(10);

            graph.AddUndirectedEdge(nodeA, nodeB);
            nodeA = graph.AddNode(7);
            graph.AddUndirectedEdge(nodeA, nodeB);
            nodeB = graph.AddNode(14);
            nodeA = graph.AddNode(-1);
            graph.AddUndirectedEdge(nodeA, nodeB);
            nodeB = graph.AddNode(1);
            graph.AddUndirectedEdge(nodeA, nodeB);
            nodeB = graph.AddNode(17);
            graph.AddUndirectedEdge(nodeA, nodeB);
        }
コード例 #10
0
ファイル: Graph.cs プロジェクト: senchov/ECS
        public static Graph <N, E> LoadGraphFromFile(string path)
        {
            Graph <N, E> loadedGraph = new Graph <N, E>();
            JSONClass    loadedJson  = JSONNode.LoadFromFile(path).AsObject;

            foreach (JSONNode jsonNode in loadedJson["nodes"].Children)
            {
                N node = JsonUtility.FromJson <N>(jsonNode);
                loadedGraph.AddNode(node);
            }

            foreach (JSONNode jsonNode in loadedJson["edges"].Children)
            {
                E edge = JsonUtility.FromJson <E>(jsonNode);
                loadedGraph.AddEdge(edge, edge.From);
            }

            return(loadedGraph);
        }
コード例 #11
0
        /// <summary>
        /// Test adding a node to an empty graph
        /// </summary>
        static void TestAddNodeEmptyGraph()
        {
            Graph <int> graph   = new Graph <int>();
            bool        success = graph.AddNode(4);

            Console.Write("TestAddNodeEmptyGraph: ");
            string graphString = graph.ToString();

            if (graphString.Equals("[Node Value: 4 Neighbors: ]") &&
                graph.Count == 1 &&
                success)
            {
                Console.WriteLine("Passed");
            }
            else
            {
                Console.WriteLine("FAILED!!! Expected: [Node Value: 4  " +
                                  "Neighbors: ], 1, and true Actual: " + graphString +
                                  ", " + graph.Count + " and " +
                                  success);
            }
        }
コード例 #12
0
ファイル: Form1.cs プロジェクト: sampletext-hw/Graphs
        private void pictureBoxFrame_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                Graph.AddNode(new Node {
                    X = e.X, Y = e.Y
                });
            }
            else if (e.Button == MouseButtons.Left)
            {
                var node         = Graph.Nodes.FirstOrDefault(t => t.ContainsPoint(e.X, e.Y));
                var selectedNode = SelectedNodes.FirstOrDefault(t => t.ContainsPoint(e.X, e.Y));

                if (node != null)
                {
                    node.IsHighlighted = true;
                    Graph.Nodes.Remove(node);
                    SelectedNodes.Add(node);
                }
                else if (selectedNode != null)
                {
                    selectedNode.IsHighlighted = false;
                    Graph.Nodes.Add(selectedNode);
                    SelectedNodes.Remove(selectedNode);
                }
                else
                {
                    _dragging   = true;
                    _dragStartX = e.X;
                    _dragStartY = e.Y;
                    _dragEndX   = e.X;
                    _dragEndY   = e.Y;
                }
            }

            Draw();
            UpdateConnectionsListbox();
        }
コード例 #13
0
ファイル: Program.cs プロジェクト: spssdc/Graphs
        static void Main()
        {
            // Create the instance of a graph called myGraph
            Graph         myGraph = new Graph();
            List <string> myNodes = new List <string> {
                "A", "B", "C", "D", "E", "F", "G", "H"
            };

            Console.WriteLine("Creating graph");

            // Add nodes names A--H to the graph
            foreach (string s in myNodes)
            {
                myGraph.AddNode(s);
            }
            myGraph.PrintNodes();

            // Add the edges
            myGraph.AddEdge("A", "B", 2);
            myGraph.AddEdge("A", "C", 10);
            myGraph.AddEdge("B", "D", 3);
            myGraph.AddEdge("C", "D", 2);
            myGraph.AddEdge("B", "E", 9);
            myGraph.AddEdge("D", "F", 11);
            myGraph.AddEdge("E", "F", 5);
            myGraph.AddEdge("C", "G", 8);
            myGraph.AddEdge("D", "G", 7);
            myGraph.AddEdge("F", "H", 6);
            myGraph.AddEdge("G", "H", 1);

            Console.WriteLine("Graph created, algorithms next...");
            Console.WriteLine("BFS from A...");
            myGraph.BFS("A");
            Console.WriteLine("Shortest path from A to H");
            myGraph.Dijkstra("A", "H");
        }
コード例 #14
0
        /*
         * Format
         * x,y,index; x,y,index; x,y,index; x,y,index - Vertexes
         * index|index,index,index; index|index,index - Adjency
         */

        public static void Load(string file)
        {
            Graph.Clear();

            StreamReader reader = new StreamReader(@file, true);
            string       line   = null;
            int          index  = 0;

            while ((line = reader.ReadLine()) != null)
            {
                if (index == 0) // Vertexes data
                {
                    string[] arr = line.Split(';');

                    for (int i = 0; i < arr.Length; i++)
                    {
                        string[] data = arr[i].Split('.');

                        if (data.Length < 3)
                        {
                            continue;
                        }

                        GraphNode node = new GraphNode();

                        node.Index = int.Parse(data[2]);
                        node.IndexLabel.Content = node.Index;

                        Canvas.SetLeft(node, double.Parse(data[0]));
                        Canvas.SetTop(node, double.Parse(data[1]));
                        MainWindow.GetInstance().CanvasGrid.Children.Add(node);

                        Canvas.SetZIndex(node, 1);
                        Graph.AddNode(node);
                    }
                }

                if (index == 1) // Adjency data
                {
                    string[] arr = line.Split(';');
                    for (int i = 0; i < arr.Length; i++)
                    {
                        string[] keyData = arr[i].Split('|');

                        if (keyData.Length < 2)
                        {
                            continue;
                        }

                        int       key  = int.Parse(keyData[0]);
                        GraphNode node = Graph.GetNode(key);

                        if (node != null)
                        {
                            string[] neighbours = keyData[1].Split(',');

                            for (int j = 0; j < neighbours.Length - 1; j++)
                            {
                                int       nKey = int.Parse(neighbours[j]);
                                GraphNode n    = Graph.GetNode(nKey);

                                if (n != null)
                                {
                                    GraphEdge edge = Graph.Wire(node, n);

                                    if (edge != null)
                                    {
                                        MainWindow.GetInstance().CanvasGrid.Children.Add(edge.EdgeLine);
                                        Canvas.SetZIndex(edge.EdgeLine, 0);
                                    }
                                }
                            }
                        }
                    }
                }

                index++;
            }
        }
コード例 #15
0
ファイル: Program.cs プロジェクト: VladimirDimov/DSA
        static void Main()
        {
            var reader = new StreamReader("../../input/2.txt");
            Console.SetIn(reader);

            var firstInputLineParams = Console.ReadLine()
                .Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
                .Select(x => int.Parse(x))
                .ToArray();

            var numberOfBuildings = firstInputLineParams[0];
            var numberOfStreets = firstInputLineParams[1];
            var numberOfHospitals = firstInputLineParams[2];

            var hospitals = new HashSet<int>();
            var readHospitals = Console.ReadLine()
            .Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
            .Select(x => int.Parse(x));

            foreach (var h in readHospitals)
            {
                hospitals.Add(h);
            }

            var graph = new Graph<int>();
            var connections = new List<int[]>();

            for (int i = 0; i < numberOfStreets; i++)
            {
                connections.Add(Console.ReadLine()
                    .Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
                    .Select(x => int.Parse(x))
                    .ToArray());
            }

            // AddNodesToGraph
            foreach (var connection in connections)
            {
                var fromNode = connection[0];
                var toNode = connection[1];
                var distance = connection[2];

                if (!graph.ContainsNode(fromNode))
                {
                    graph.AddNode(fromNode);
                }

                if (!graph.ContainsNode(toNode))
                {
                    graph.AddNode(toNode);
                }

                graph.AddConnection(fromNode, toNode, distance, true);
            }

            var distanceCalc = new DistanceCalculator<int>();

            var minDist = int.MaxValue;
            foreach (var hospital in hospitals)
            {
                var dist = distanceCalc.CalculateDistances(graph, hospital)
                    .Where(x => !hospitals.Contains(x.Key))
                    .Sum(x => x.Value);

                if (minDist > dist)
                {
                    minDist = dist;
                }
            }

            Console.WriteLine(minDist);
        }
コード例 #16
0
        static void Main(string[] args)
        {
            // Undirected and unweighted edges
            // Graph<int> graph = new Graph<int>(false, false);

            // Node<int> n1 = graph.AddNode(1);
            // Node<int> n2 = graph.AddNode(2);
            // Node<int> n3 = graph.AddNode(3);
            // Node<int> n4 = graph.AddNode(4);
            // Node<int> n5 = graph.AddNode(5);
            // Node<int> n6 = graph.AddNode(6);
            // Node<int> n7 = graph.AddNode(7);
            // Node<int> n8 = graph.AddNode(8);

            // graph.AddEdge(n1, n2);
            // graph.AddEdge(n1, n3);
            // graph.AddEdge(n2, n4);
            // graph.AddEdge(n3, n4);
            // graph.AddEdge(n4, n5);
            // graph.AddEdge(n4, n8);
            // graph.AddEdge(n5, n6);
            // graph.AddEdge(n5, n7);
            // graph.AddEdge(n5, n8);
            // graph.AddEdge(n6, n7);
            // graph.AddEdge(n7, n8);

            // ---

            // Undirected and weighted edges
            // Graph<int> graph = new Graph<int>(false, true);

            // Node<int> n1 = graph.AddNode(1);
            // Node<int> n2 = graph.AddNode(2);
            // Node<int> n3 = graph.AddNode(3);
            // Node<int> n4 = graph.AddNode(4);
            // Node<int> n5 = graph.AddNode(5);
            // Node<int> n6 = graph.AddNode(6);
            // Node<int> n7 = graph.AddNode(7);
            // Node<int> n8 = graph.AddNode(8);

            // graph.AddEdge(n1, n2, 3);
            // graph.AddEdge(n1, n3, 5);
            // graph.AddEdge(n2, n4, 4);
            // graph.AddEdge(n3, n4, 12);
            // graph.AddEdge(n4, n5, 9);
            // graph.AddEdge(n4, n8, 8);
            // graph.AddEdge(n5, n6, 4);
            // graph.AddEdge(n5, n7, 5);
            // graph.AddEdge(n5, n8, 1);
            // graph.AddEdge(n6, n7, 6);
            // graph.AddEdge(n7, n8, 20);
            // graph.AddEdge(n2, n6, 20);
            // graph.AddEdge(n2, n5, 20);

            // ---

            // Directed and weighted edges
            Graph <int> graph = new Graph <int>(true, true);

            Node <int> n1 = graph.AddNode(1);
            Node <int> n2 = graph.AddNode(2);
            Node <int> n3 = graph.AddNode(3);
            Node <int> n4 = graph.AddNode(4);
            Node <int> n5 = graph.AddNode(5);
            Node <int> n6 = graph.AddNode(6);
            Node <int> n7 = graph.AddNode(7);
            Node <int> n8 = graph.AddNode(8);

            graph.AddEdge(n1, n2, 9);
            graph.AddEdge(n1, n3, 5);
            graph.AddEdge(n2, n1, 3);
            graph.AddEdge(n2, n4, 18);
            graph.AddEdge(n3, n4, 12);
            graph.AddEdge(n4, n2, 2);
            graph.AddEdge(n4, n8, 8);
            graph.AddEdge(n5, n4, 9);
            graph.AddEdge(n5, n6, 2);
            graph.AddEdge(n5, n7, 5);
            graph.AddEdge(n5, n8, 3);
            graph.AddEdge(n6, n7, 1);
            graph.AddEdge(n7, n5, 4);
            graph.AddEdge(n7, n8, 6);
            graph.AddEdge(n8, n5, 3);

            Console.WriteLine("Minimum Spanning Tree - Kruskal's Algorithm:");
            List <Edge <int> > mstKruskal = graph.MinimumSpanningTreeKruskal();

            mstKruskal.ForEach(e => Console.WriteLine(e));

            Console.WriteLine("\nMinimum Spanning Tree - Prim's Algorithm:");
            List <Edge <int> > mstPrim = graph.MinimumSpanningTreePrim();

            mstPrim.ForEach(e => Console.WriteLine(e));

            Console.WriteLine("\nShortest Path - Dijkstra's Algorithm:");
            List <Edge <int> > path = graph.GetShortestPathDijkstra(n1, n5);

            path.ForEach(e => Console.WriteLine(e));

            Console.WriteLine("\nColoring the graph:");
            int[] colors = graph.Color();
            for (int i = 0; i < colors.Length; i++)
            {
                Console.WriteLine($"Node {graph.Nodes[i].Data}: {colors[i]}");
            }

            Console.WriteLine("\nDepth-First Search:");
            List <Node <int> > dfsNodes = graph.DFS();

            dfsNodes.ForEach(n => Console.WriteLine(n));

            Console.WriteLine("\nBreath-First Search:");
            List <Node <int> > bfsNodes = graph.BFS();

            bfsNodes.ForEach(n => Console.WriteLine(n));
        }
コード例 #17
0
        static void Main(string[] args)
        {
            Graph.AddNode(new Node(7, "0", new Coordinate(0, 0)));
            Graph.AddNode(new Node(7, "1", new Coordinate(50, 100)));
            Graph.AddNode(new Node(7, "2", new Coordinate(100, 0)));
            Graph.AddNode(new Node(7, "3", new Coordinate(0, 200)));
            Graph.AddNode(new Node(7, "4", new Coordinate(250, 200)));
            Graph.AddNode(new Node(7, "5", new Coordinate(50, 250)));
            Graph.AddNode(new Node(7, "6", new Coordinate(150, 250)));

            Graph.AddTwoWayEdge(new Edge(7, Graph.SetOfNodes[0], Graph.SetOfNodes[1]));
            Graph.AddTwoWayEdge(new Edge(5, Graph.SetOfNodes[0], Graph.SetOfNodes[3]));
            Graph.AddTwoWayEdge(new Edge(8, Graph.SetOfNodes[1], Graph.SetOfNodes[2]));
            Graph.AddTwoWayEdge(new Edge(7, Graph.SetOfNodes[1], Graph.SetOfNodes[4]));
            Graph.AddTwoWayEdge(new Edge(9, Graph.SetOfNodes[1], Graph.SetOfNodes[3]));
            Graph.AddTwoWayEdge(new Edge(5, Graph.SetOfNodes[2], Graph.SetOfNodes[4]));
            Graph.AddTwoWayEdge(new Edge(15, Graph.SetOfNodes[3], Graph.SetOfNodes[4]));
            Graph.AddTwoWayEdge(new Edge(6, Graph.SetOfNodes[3], Graph.SetOfNodes[5]));
            Graph.AddTwoWayEdge(new Edge(8, Graph.SetOfNodes[5], Graph.SetOfNodes[4]));
            Graph.AddTwoWayEdge(new Edge(11, Graph.SetOfNodes[5], Graph.SetOfNodes[6]));
            Graph.AddTwoWayEdge(new Edge(9, Graph.SetOfNodes[6], Graph.SetOfNodes[4]));

            NewGraph.AddNode(new Node(7, "0", new Coordinate(0, 0)));
            NewGraph.AddNode(new Node(7, "1", new Coordinate(50, 100)));
            NewGraph.AddNode(new Node(7, "2", new Coordinate(100, 0)));
            NewGraph.AddNode(new Node(7, "3", new Coordinate(0, 200)));
            NewGraph.AddNode(new Node(7, "4", new Coordinate(500, 100)));
            NewGraph.AddNode(new Node(7, "5", new Coordinate(50, 250)));
            NewGraph.AddNode(new Node(7, "6", new Coordinate(150, 250)));

            NewGraph.AddOneWayEdge(new Edge(7, NewGraph.SetOfNodes[0], NewGraph.SetOfNodes[1]));
            NewGraph.AddOneWayEdge(new Edge(5, NewGraph.SetOfNodes[0], NewGraph.SetOfNodes[3]));
            NewGraph.AddOneWayEdge(new Edge(8, NewGraph.SetOfNodes[1], NewGraph.SetOfNodes[2]));
            NewGraph.AddOneWayEdge(new Edge(7, NewGraph.SetOfNodes[1], NewGraph.SetOfNodes[4]));
            NewGraph.AddOneWayEdge(new Edge(9, NewGraph.SetOfNodes[1], NewGraph.SetOfNodes[3]));
            NewGraph.AddOneWayEdge(new Edge(5, NewGraph.SetOfNodes[2], NewGraph.SetOfNodes[4]));
            NewGraph.AddOneWayEdge(new Edge(15, NewGraph.SetOfNodes[3], NewGraph.SetOfNodes[4]));
            NewGraph.AddOneWayEdge(new Edge(6, NewGraph.SetOfNodes[3], NewGraph.SetOfNodes[5]));
            NewGraph.AddOneWayEdge(new Edge(8, NewGraph.SetOfNodes[5], NewGraph.SetOfNodes[4]));
            NewGraph.AddOneWayEdge(new Edge(11, NewGraph.SetOfNodes[5], NewGraph.SetOfNodes[6]));
            NewGraph.AddOneWayEdge(new Edge(9, NewGraph.SetOfNodes[4], NewGraph.SetOfNodes[6]));

            DepthFirstSearchAlgorithm   DFS = new DepthFirstSearchAlgorithm(Graph);
            BreadthFirstSearchAlgorithm BFS = new BreadthFirstSearchAlgorithm(Graph);
            KruscalAlgorithm            KruskalTreeSearch  = new KruscalAlgorithm(Graph);
            PrimAlgorithm          PrimTreeSearch          = new PrimAlgorithm(Graph);
            BellmanFordAlgorithm   BellmanFordPathSearch   = new BellmanFordAlgorithm(Graph);
            DijkstraAlgorithm      DijkstraPathSearch      = new DijkstraAlgorithm(Graph);
            FloydWarshallAlgorithm FloydWarshallPathSearch = new FloydWarshallAlgorithm(Graph);
            JohnsonAlgorithm       JohnsonPathSearch       = new JohnsonAlgorithm(Graph);
            AStarAlgorithm         AStarPathSearch         = new AStarAlgorithm(Graph);

            Console.WriteLine("[Current Graph]\n", Color.Green);

            Console.WriteLine("[0]        [2]");
            Console.WriteLine("|\\         /|");
            Console.WriteLine("| \\ 7    8/ |");
            Console.WriteLine("|  \\     /  |5");
            Console.WriteLine("|5  \\   /   |");
            Console.WriteLine("|    [1]    |");
            Console.WriteLine("| 9 /   \\7  |");
            Console.WriteLine("|  /     \\  |");
            Console.WriteLine("| /   15  \\ |");
            Console.WriteLine("[3]--------[4]");
            Console.WriteLine(" \\        /  \\ ");
            Console.WriteLine("  \\     8/    \\9");
            Console.WriteLine(" 6 \\    /      \\");
            Console.WriteLine("    \\  /        \\");
            Console.WriteLine("    [5]---------[6]");
            Console.WriteLine("           11\n");

            Console.WriteLine("[1 : Depth First Search]\n", Color.Green);

            DFS.DepthFirstSearch(Graph.SetOfNodes[0]);

            Utilities.PrintResult(DFS.ResultOfSearching);

            Console.WriteLine();

            Console.WriteLine("[2 : Breadth First Search]\n", Color.Green);

            BFS.BreadthFirstSearch(Graph.SetOfNodes[0]);

            Utilities.PrintResult(BFS.ResultOfSearching);

            Console.WriteLine();

            FordFulkersonAlgorithm FordFulkersonStreamSearch = new FordFulkersonAlgorithm(NewGraph);

            Console.WriteLine($"[3 : Kruskal Tree Search]\n", Color.Green);

            KruskalTreeSearch.FindMinimumSpanningTree();

            Utilities.PrintResult(KruskalTreeSearch.MinimumSpanningTree);

            Console.WriteLine();

            Console.WriteLine($"[4 : Prim Tree Search]\n", Color.Green);

            PrimTreeSearch.FindMinimumSpanningTree();

            Utilities.PrintResult(PrimTreeSearch.MinimumSpanningTree);

            Console.WriteLine();

            Console.WriteLine("[5 : Bellman-Ford Path Search]\n", Color.Green);

            BellmanFordPathSearch.FindTheShortestPathes(Graph.SetOfNodes[0]);

            Utilities.PrintResult(BellmanFordPathSearch.ShortestPathes, Graph.SetOfNodes[0]);

            Console.WriteLine("[6 : Dijkstra Path Search]\n", Color.Green);

            DijkstraPathSearch.FindTheShortestPathes(Graph.SetOfNodes[0]);

            Utilities.PrintResult(DijkstraPathSearch.ShortestPathes, Graph.SetOfNodes[0]);

            FloydWarshallPathSearch.FindAllTheShortestPathes();

            Console.WriteLine("[7 : Floyd-Warshall Path Search]\n", Color.Green);

            Utilities.PrintResult(FloydWarshallPathSearch.MatrixOfTheShortesPathes);

            Console.WriteLine();

            JohnsonPathSearch.FindAllTheShortestPathes();

            Console.WriteLine("[8 : Johnson Path Search]\n", Color.Green);

            Utilities.PrintResult(JohnsonPathSearch.MatrixOfTheShortesPathes);

            Console.WriteLine();

            Console.WriteLine("[9 : Ford-Fulkerson Stream Search]\n", Color.Green);

            FordFulkersonStreamSearch.FindMaximumFlowWithDFSRealization(NewGraph.SetOfNodes[0], NewGraph.SetOfNodes[6]);

            Console.WriteLine($"Maximum stream capacity is : {FordFulkersonStreamSearch.CapacityOfFlow}");

            Console.WriteLine();

            Console.WriteLine("[10 : A* Path Search]\n", Color.Green);

            AStarPathSearch.FindTheShortesPath(Graph.SetOfNodes[0], Graph.SetOfNodes[6]);

            Utilities.PrintResult(AStarPathSearch.ShortesPath);

            Console.ReadKey();
        }
コード例 #18
0
        static void Main(string[] args)
        {
            Graph <string> graph = new Graph <string>(false, true);

            Node <string> nodeB1 = graph.AddNode("B1");
            Node <string> nodeB2 = graph.AddNode("B2");
            Node <string> nodeB3 = graph.AddNode("B3");
            Node <string> nodeB4 = graph.AddNode("B4");
            Node <string> nodeB5 = graph.AddNode("B5");
            Node <string> nodeB6 = graph.AddNode("B6");
            Node <string> nodeR1 = graph.AddNode("R1");
            Node <string> nodeR2 = graph.AddNode("R2");
            Node <string> nodeR3 = graph.AddNode("R3");
            Node <string> nodeR4 = graph.AddNode("R4");
            Node <string> nodeR5 = graph.AddNode("R5");
            Node <string> nodeR6 = graph.AddNode("R6");

            graph.AddEdge(nodeB1, nodeB2, 2);
            graph.AddEdge(nodeB1, nodeB3, 20);
            graph.AddEdge(nodeB1, nodeB4, 30);
            graph.AddEdge(nodeB2, nodeB3, 30);
            graph.AddEdge(nodeB2, nodeB4, 20);
            graph.AddEdge(nodeB3, nodeB4, 2);
            graph.AddEdge(nodeB2, nodeR2, 25);
            graph.AddEdge(nodeB4, nodeR4, 25);
            graph.AddEdge(nodeR1, nodeR2, 1);
            graph.AddEdge(nodeR2, nodeR3, 1);
            graph.AddEdge(nodeR3, nodeR4, 1);
            graph.AddEdge(nodeR1, nodeR5, 75);
            graph.AddEdge(nodeR3, nodeR6, 100);
            graph.AddEdge(nodeR5, nodeR6, 3);
            graph.AddEdge(nodeR6, nodeB5, 3);
            graph.AddEdge(nodeB5, nodeB6, 6);
            graph.AddEdge(nodeR6, nodeB6, 10);

            Console.WriteLine("Minimum Spanning Tree - Kruskal's Algorithm:");
            List <Edge <string> > mstKruskal = graph.MinimumSpanningTreeKruskal();

            mstKruskal.ForEach(e => Console.WriteLine(e));
            Console.WriteLine("Total cost: " + mstKruskal.Sum(e => e.Weight));

            Console.WriteLine("\nMinimum Spanning Tree - Prim's Algorithm:");
            List <Edge <string> > mstPrim = graph.MinimumSpanningTreePrim();

            mstPrim.ForEach(e => Console.WriteLine(e));
            Console.WriteLine("Total cost: " + mstPrim.Sum(e => e.Weight));
        }
コード例 #19
0
        static void Main(string[] args)
        {
            Graph <string> graph = new Graph <string>(false, false);

            Node <string> nodePK = graph.AddNode("PK");
            Node <string> nodeLU = graph.AddNode("LU");
            Node <string> nodePD = graph.AddNode("PD");
            Node <string> nodeWM = graph.AddNode("WM");
            Node <string> nodeMZ = graph.AddNode("MZ");
            Node <string> nodeSW = graph.AddNode("SW");
            Node <string> nodeMA = graph.AddNode("MA");
            Node <string> nodeSL = graph.AddNode("SL");
            Node <string> nodeLD = graph.AddNode("LD");
            Node <string> nodeKP = graph.AddNode("KP");
            Node <string> nodePM = graph.AddNode("PM");
            Node <string> nodeZP = graph.AddNode("ZP");
            Node <string> nodeWP = graph.AddNode("WP");
            Node <string> nodeLB = graph.AddNode("LB");
            Node <string> nodeDS = graph.AddNode("DS");
            Node <string> nodeOP = graph.AddNode("OP");

            graph.AddEdge(nodePK, nodeLU);
            graph.AddEdge(nodePK, nodeSW);
            graph.AddEdge(nodePK, nodeMA);
            graph.AddEdge(nodeLU, nodeSW);
            graph.AddEdge(nodeLU, nodeMZ);
            graph.AddEdge(nodeLU, nodePD);
            graph.AddEdge(nodePD, nodeMZ);
            graph.AddEdge(nodePD, nodeWM);
            graph.AddEdge(nodeWM, nodeKP);
            graph.AddEdge(nodeWM, nodePM);
            graph.AddEdge(nodeWM, nodeMZ);
            graph.AddEdge(nodeMZ, nodeKP);
            graph.AddEdge(nodeMZ, nodeLD);
            graph.AddEdge(nodeMZ, nodeSW);
            graph.AddEdge(nodeSW, nodeLD);
            graph.AddEdge(nodeSW, nodeSL);
            graph.AddEdge(nodeSW, nodeMA);
            graph.AddEdge(nodeMA, nodeSL);
            graph.AddEdge(nodeSL, nodeOP);
            graph.AddEdge(nodeSL, nodeLD);
            graph.AddEdge(nodeLD, nodeOP);
            graph.AddEdge(nodeLD, nodeWP);
            graph.AddEdge(nodeLD, nodeKP);
            graph.AddEdge(nodeKP, nodeWP);
            graph.AddEdge(nodeKP, nodePM);
            graph.AddEdge(nodePM, nodeZP);
            graph.AddEdge(nodePM, nodeLB);
            graph.AddEdge(nodePM, nodeWP);
            graph.AddEdge(nodeZP, nodeLB);
            graph.AddEdge(nodeWP, nodeDS);
            graph.AddEdge(nodeWP, nodeOP);
            graph.AddEdge(nodeWP, nodeLB);
            graph.AddEdge(nodeLB, nodeDS);
            graph.AddEdge(nodeDS, nodeOP);

            int[] colors = graph.Color();
            for (int i = 0; i < colors.Length; i++)
            {
                Console.WriteLine($"{graph.Nodes[i].Data}: {colors[i]}");
            }
        }
コード例 #20
0
ファイル: Program.cs プロジェクト: spvinod1986/DataStructures
        static void Main(string[] args)
        {
            var graph = new Graph();

            graph.AddNode("David");
            graph.AddNode("John");
            graph.AddNode("Peter");
            graph.AddEdge("David", "John");
            graph.AddEdge("David", "Peter");
            graph.AddEdge("John", "Peter");
            graph.RemoveEdge("David", "Peter");
            graph.RemoveEdge("A", "B");
            graph.RemoveNode("John");
            graph.Print();

            var graph1 = new Graph();

            graph1.AddNode("A");
            graph1.AddNode("B");
            graph1.AddNode("C");
            graph1.AddNode("D");
            graph1.AddEdge("A", "B");
            graph1.AddEdge("B", "D");
            graph1.AddEdge("D", "C");
            graph1.AddEdge("A", "C");
            graph1.TraverseDepthFirstRecursive("A");
            graph1.TraverseDepthFirstIterative("A");
            graph1.TraverseBreadthFirstIterative("A");

            var graph2 = new Graph();

            graph2.AddNode("X");
            graph2.AddNode("A");
            graph2.AddNode("B");
            graph2.AddNode("P");
            graph2.AddEdge("X", "A");
            graph2.AddEdge("X", "B");
            graph2.AddEdge("A", "P");
            graph2.AddEdge("B", "P");
            var nodes = graph2.TopologicalSort();

            foreach (var node in nodes)
            {
                System.Console.WriteLine(node);
            }

            var graph3 = new Graph();

            graph3.AddNode("A");
            graph3.AddNode("B");
            graph3.AddNode("C");
            graph3.AddEdge("A", "B");
            graph3.AddEdge("B", "C");
            graph3.AddEdge("C", "A");
            System.Console.WriteLine(graph3.HasCycle());

            var weightedGraph = new WeightedGraph();

            weightedGraph.AddNode("A");
            weightedGraph.AddNode("B");
            weightedGraph.AddNode("C");
            weightedGraph.AddEdge("A", "B", 3);
            weightedGraph.AddEdge("A", "C", 2);
            weightedGraph.Print();

            var weightedGraph1 = new WeightedGraph();

            weightedGraph1.AddNode("A");
            weightedGraph1.AddNode("B");
            weightedGraph1.AddNode("C");
            weightedGraph1.AddEdge("A", "B", 1);
            weightedGraph1.AddEdge("B", "C", 2);
            weightedGraph1.AddEdge("A", "C", 10);
            var path = weightedGraph1.GetShortestPath("A", "C");

            System.Console.WriteLine(path);

            var weightedGraph2 = new WeightedGraph();

            weightedGraph2.AddNode("A");
            weightedGraph2.AddNode("B");
            weightedGraph2.AddNode("C");
            weightedGraph2.AddEdge("A", "B", 0);
            weightedGraph2.AddEdge("B", "C", 0);
            weightedGraph2.AddEdge("C", "A", 0);
            System.Console.WriteLine(weightedGraph2.HasCycle());

            var weightedGraph3 = new WeightedGraph();

            weightedGraph3.AddNode("A");
            weightedGraph3.AddNode("B");
            weightedGraph3.AddNode("C");
            weightedGraph3.AddNode("D");
            weightedGraph3.AddEdge("A", "B", 3);
            weightedGraph3.AddEdge("B", "D", 4);
            weightedGraph3.AddEdge("C", "D", 5);
            weightedGraph3.AddEdge("A", "C", 1);
            weightedGraph3.AddEdge("B", "C", 2);
            var tree = weightedGraph3.GetMinimumSpanningTree();

            tree.Print();
        }
コード例 #21
0
        public static void Main(string[] args)
        {
            string path   = "../../../connectionDB.txt";
            bool   create = true;
            Graph  g      = null;

            if (create)
            {
                g = new Graph();

                for (int i = 0; i <= 20; ++i)
                {
                    g.AddNode(new Node(i));
                }


                int[] line0 = { 0, 1, 2, 3, 4, 5, 6, 7, 8 };
                for (int i = 0; i < line0.Length - 1; ++i)
                {
                    g.AddEdge(new Edge(line0[i], line0[i + 1], Color: 0));
                }

                int[] line1 = { 0, 1, 2, 3, 4, 9, 11, 12, 13 };
                for (int i = 0; i < line1.Length - 1; ++i)
                {
                    g.AddEdge(new Edge(line1[i], line1[i + 1], Color: 1));
                }

                int[] line2 = { 14, 3, 15, 16, 17, 18 };
                for (int i = 0; i < line2.Length - 1; ++i)
                {
                    g.AddEdge(new Edge(line2[i], line2[i + 1], Color: 2));
                }

                int[] line3 = { 0, 3, 5, 8 };
                for (int i = 0; i < line3.Length - 1; ++i)
                {
                    g.AddEdge(new Edge(line3[i], line3[i + 1], Color: 3));
                }

                int[] line4 = { 1, 2, 3, 4, 9, 10, 20, 13, 19, 18 };
                for (int i = 0; i < line4.Length - 1; ++i)
                {
                    g.AddEdge(new Edge(line4[i], line4[i + 1], Color: 4));
                }
            }
            else
            {
                if (File.Exists(path) == false)
                {
                    throw new FileNotFoundException();
                }
                g = Graph.FromFile(path);
            }
            //Dijkstra - WORKING :-)

            var v = Algo.DijkstraAlgorithm(8, 19, g);

            foreach (var p in v)
            {
                Console.WriteLine(p.Id);
            }

            if (create)
            {
                g.SaveToFile(path);
            }
        }
コード例 #22
0
        static void Main(string[] args)
        {
            string[] lines = new string[]
            {
                "0011100000111110000011111",
                "0011100000111110000011111",
                "0011100000111110000011111",
                "0000000000011100000011111",
                "0000001110000000000011111",
                "0001001110011100000011111",
                "1111111111111110111111100",
                "1111111111111110111111101",
                "1111111111111110111111100",
                "0000000000000000111111110",
                "0000000000000000111111100",
                "0001111111001100000001101",
                "0001111111001100000001100",
                "0001100000000000111111110",
                "1111100000000000111111100",
                "1111100011001100100010001",
                "1111100011001100001000100"
            };
            bool[][] map = new bool[lines.Length][];
            for (int i = 0; i < lines.Length; i++)
            {
                map[i] = lines[i]
                         .Select(c => int.Parse(c.ToString()) == 0)
                         .ToArray();
            }

            Graph <string> graph = new Graph <string>(false, true);

            for (int i = 0; i < map.Length; i++)
            {
                for (int j = 0; j < map[i].Length; j++)
                {
                    if (map[i][j])
                    {
                        Node <string> from = graph.AddNode($"{i}-{j}");

                        if (i > 0 && map[i - 1][j])
                        {
                            Node <string> to = graph.Nodes.Find(n => n.Data == $"{i - 1}-{j}");
                            graph.AddEdge(from, to, 1);
                        }

                        if (j > 0 && map[i][j - 1])
                        {
                            Node <string> to = graph.Nodes.Find(n => n.Data == $"{i}-{j - 1}");
                            graph.AddEdge(from, to, 1);
                        }
                    }
                }
            }

            Node <string>         source = graph.Nodes.Find(n => n.Data == "0-0");
            Node <string>         target = graph.Nodes.Find(n => n.Data == "16-24");
            List <Edge <string> > path   = graph.GetShortestPathDijkstra(source, target);

            Console.OutputEncoding = Encoding.UTF8;
            for (int row = 0; row < map.Length; row++)
            {
                for (int column = 0; column < map[row].Length; column++)
                {
                    ConsoleColor color = map[row][column] ? ConsoleColor.Green : ConsoleColor.Red;
                    if (path.Any(e => e.From.Data == $"{row}-{column}" || e.To.Data == $"{row}-{column}"))
                    {
                        color = ConsoleColor.White;
                    }

                    Console.ForegroundColor = color;
                    Console.Write("\u25cf ");
                }
                Console.WriteLine();
            }

            Console.ForegroundColor = ConsoleColor.Gray;
        }