C#语言实现最短路径算法(Shortest Path)在C#中实现最短路径算法,可以使用经典的Dijkstra算法。以下是一个使用Dijkstra算法来计算图中单源最短路径的示例:
using System;
using System.Collections.Generic;
class Dijkstra
{
public class Edge
{
public int Target { get; }
public int Weight { get; }
public Edge(int target, int weight)
{
Target = target;
Weight = weight;
}
}
public class Graph
{
private int vertices;
private List<Edge>[] adjacencyList;
public Graph(int vertices)
{
this.vertices = vertices;
adjacencyList = new List<Edge>[vertices];
for (int i = 0; i < vertices; i++)
{
adjacencyList[i] = new List<Edge>();
}
}
public void AddEdge(int source, int target, int weight)
{
adjacencyList[source].Add(new Edge(target, weight));
adjacencyList[target].Add(new Edge(source, weight)); // 如果是有向图,则去掉这一行
}
public void DijkstraAlgorithm(int startVertex)
{
bool[] visited = new bool[vertices];
int[] distances = new int[vertices];
for (int i = 0; i < vertices; i++)
{
distances[i] = int.MaxValue;
}
distances[startVertex] = 0;
SortedSet<(int Distance, int Vertex)> pq = new SortedSet<(int, int)>();
pq.Add((0, startVertex));
while (pq.Count > 0)
{
var (currentDistance, currentVertex) = pq.Min;
pq.Remove(pq.Min);
if (visited[currentVertex])
continue;
visited[currentVertex] = true;
foreach (var edge in adjacencyList[currentVertex])
{
int target = edge.Target;
int weight = edge.Weight;
if (!visited[target] && distances[currentVertex] + weight < distances[target])
{
distances[target] = distances[currentVertex] + weight;
pq.Add((distances[target], target));
}
}
}
PrintShortestPaths(startVertex, distances);
}
private void PrintShortestPaths(int startVertex, int[] distances)
{
Console.WriteLine("Vertex/tDistance from Source " + startVertex);
for (int i = 0; i < vertices; i++)
{
Console.WriteLine(i + "/t/t" + distances[i]);
}
}
}
static void Main(string[] args)
{
int vertices = 6;
Graph graph = new Graph(vertices);
graph.AddEdge(0, 1, 4);
graph.AddEdge(0, 2, 3);
graph.AddEdge(1, 2, 1);
graph.AddEdge(1, 3, 2);
graph.AddEdge(2, 3, 4);
graph.AddEdge(3, 4, 2);
graph.AddEdge(4, 5, 6);
graph.DijkstraAlgorithm(0);
}
}
这个示例中,我们创建了一个包含6个顶点的图,并添加了一些边。然后,我们从顶点0开始运行Dijkstra算法,计算并打印出从顶点0到所有其他顶点的最短路径距离。