Beispiel #1
0
 public JohnsonsGraph(int nodeCount)
 {
     this.nodeCount    = nodeCount;
     augmentedMatrix   = new int[nodeCount + 2][nodeCount + 2];
     SOURCE_NODE       = nodeCount + 1;
     potential         = new int[nodeCount + 2];
     bellmanFord       = new BellmanFordGraph(nodeCount + 1);
     dijkstras         = new DijkstrasGraph(nodeCount);
     allShortestsPaths = new int[nodeCount + 1][nodeCount + 1];
 }
Beispiel #2
0
    public void BellmanFordAlgorithm(BellmanFordGraph graph, int source)
    {
        int vertices = graph.vertices;
        int edges    = graph.edges;

        int[] distances = new int[vertices];

        for (int vertex = 0; vertex < vertices; vertex++)
        {
            distances[vertex] = int.MaxValue;
        }

        distances[source] = 0;

        for (int vertex = 0; vertex < vertices; vertex++)
        {
            for (int edge = 0; edge < edges; edges++)
            {
                int start  = graph.edgesArr[edge].source;
                int end    = graph.edgesArr[edge].destination;
                int weight = graph.edgesArr[edge].weight;
                if (distances[start] != int.MaxValue && distances[start] + weight < distances[end])
                {
                    distances[end] = distances[start] + weight;
                }
            }
        }

        for (int edge = 0; edge < edges; edge++)
        {
            int start  = graph.edgesArr[edge].source;
            int end    = graph.edgesArr[edge].destination;
            int weight = graph.edgesArr[edge].weight;
            if (distances[start] != int.MaxValue && distances[start] + weight < distances[end])
            {
                Console.WriteLine("Graph contains a negative cycle");
                return;
            }
        }

        // At this point, distance array has all shortest distances from source
    }