Dijkstra算法实现输出最短路径c#。
时间: 2024-04-12 21:31:38 浏览: 116
你好!下面是使用C#实现Dijkstra算法来输出最短路径的示例代码:
```c#
using System;
using System.Collections.Generic;
public class DijkstraAlgorithm
{
private int numVertices;
private List<List<Node>> adjacencyList;
private class Node
{
public int Vertex { get; }
public int Weight { get; }
public Node(int vertex, int weight)
{
Vertex = vertex;
Weight = weight;
}
}
public DijkstraAlgorithm(int numVertices)
{
this.numVertices = numVertices;
adjacencyList = new List<List<Node>>(numVertices);
for (int i = 0; i < numVertices; i++)
{
adjacencyList.Add(new List<Node>());
}
}
public void AddEdge(int source, int destination, int weight)
{
adjacencyList[source].Add(new Node(destination, weight));
}
public void ShortestPath(int source)
{
int[] distances = new int[numVertices];
bool[] visited = new bool[numVertices];
for (int i = 0; i < numVertices; i++)
{
distances[i] = int.MaxValue;
visited[i] = false;
}
distances[source] = 0;
for (int i = 0; i < numVertices - 1; i++)
{
int minDistanceVertex = MinimumDistance(distances, visited);
visited[minDistanceVertex] = true;
foreach (Node node in adjacencyList[minDistanceVertex])
{
if (!visited[node.Vertex] && distances[minDistanceVertex] != int.MaxValue &&
distances[minDistanceVertex] + node.Weight < distances[node.Vertex])
{
distances[node.Vertex] = distances[minDistanceVertex] + node.Weight;
}
}
}
PrintShortestPaths(distances, source);
}
private int MinimumDistance(int[] distances, bool[] visited)
{
int min = int.MaxValue;
int minIndex = -1;
for (int i = 0; i < numVertices; i++)
{
if (!visited[i] && distances[i] <= min)
{
min = distances[i];
minIndex = i;
}
}
return minIndex;
}
private void PrintShortestPaths(int[] distances, int source)
{
Console.WriteLine("Vertex\tDistance from Source");
for (int i = 0; i < numVertices; i++)
{
Console.WriteLine("{0}\t\t{1}", i, distances[i]);
}
}
public static void Main(string[] args)
{
DijkstraAlgorithm graph = new DijkstraAlgorithm(6);
graph.AddEdge(0, 1, 4);
graph.AddEdge(0, 2, 1);
graph.AddEdge(1, 3, 1);
graph.AddEdge(2, 1, 2);
graph.AddEdge(2, 3, 5);
graph.AddEdge(3, 4, 3);
graph.AddEdge(4, 1, 3);
graph.AddEdge(4, 0, 2);
int source = 0;
graph.ShortestPath(source);
}
}
```
这是一个简单的示例,你可以根据自己的需求进行修改。在示例代码中,我们首先定义了一个 `DijkstraAlgorithm` 类来实现Dijkstra算法。然后,我们可以使用 `AddEdge` 方法添加图的边。最后,在 `Main` 方法中,我们创建了一个具有6个顶点的图,并计算从指定源点到其他各个顶点的最短路径。
希望能帮到你!如果你还有其他问题,请随时提问。
阅读全文