예제 #1
0
        private float Weight(int vertexA, int vertexB, WeightedDiAdjacencyMatrix graph)
        {
            var edge = graph.GetEdge(vertexA, vertexB);

            if (edge == null)
            {
                return(float.PositiveInfinity);
            }
            else
            {
                return(edge.Weight);
            }
        }
예제 #2
0
        public float[] RunDijkstraAlg(WeightedDiAdjacencyMatrix graph, int vertex)
        {
            vertex -= 1;
            var shortestPathsMatrix = new float[graph.Order];

            shortestPathsMatrix[vertex] = 0f;
            var neighbours      = graph.Neighbours(vertex + 1);
            var verticleToCheck = new List <int>();

            for (int i = 1; i <= graph.Order; i++)
            {
                if (i == vertex + 1)
                {
                    continue;
                }

                verticleToCheck.Add(i - 1);

                if (neighbours.Contains(i))
                {
                    shortestPathsMatrix[i - 1] = graph.GetEdge(vertex, i - 1).Weight;
                }
                else
                {
                    shortestPathsMatrix[i - 1] = float.PositiveInfinity;
                }
            }

            Console.WriteLine("Dijkstra:");
            Console.Write("iter 0:\t");
            PrintValues(shortestPathsMatrix);
            int iter = 1;

            while (verticleToCheck.Count > 0)
            {
                var minIndex = IndexOfMinElement(shortestPathsMatrix, verticleToCheck);
                verticleToCheck.Remove(minIndex);

                foreach (var item in verticleToCheck)
                {
                    shortestPathsMatrix[item] = Math.Min(shortestPathsMatrix[item], shortestPathsMatrix[minIndex] + Weight(minIndex, item, graph));
                }
                Console.Write("iter " + iter + ":\t");
                iter++;
                PrintValues(shortestPathsMatrix);
            }

            return(shortestPathsMatrix);
        }