利用D算法实现寻找图的最短路径,算法中包含输入图并存储图的代码
时间: 2024-10-15 09:21:03 浏览: 14
Dijkstra算法(迪杰斯特拉算法)是一种用于查找有向或无向加权图中两个顶点之间最短路径的算法。它通常用作求解单源最短路径问题。以下是使用C#实现的基本步骤:
首先,你需要创建一个数据结构来表示图,例如邻接矩阵或邻接列表。这里我们用邻接列表(Adjacency List)为例,因为对于大型图,它比邻接矩阵更节省空间。
```csharp
public class Node {
public int Id { get; set; }
public List<Edge> Edges { get; set; }
public Node(int id) {
Id = id;
Edges = new List<Edge>();
}
}
public class Edge {
public int Target { get; set; }
public double Distance { get; set; }
public Edge(int target, double distance) {
Target = target;
Distance = distance;
}
}
```
然后,你可以定义Dijkstra算法的主要逻辑:
```csharp
public static Dictionary<int, double> Dijkstra(Node startNode, List<Node> graphNodes) {
var distances = new Dictionary<int, double>(graphNodes.Count);
var unvisited = new PriorityQueue<Edge>((a, b) => a.Distance.CompareTo(b.Distance));
foreach (var node in graphNodes) {
distances[node.Id] = double.MaxValue;
}
distances[startNode.Id] = 0;
unvisited.Enqueue(new Edge(startNode.Id, 0));
while (unvisited.Count > 0) {
var currentEdge = unvisited.Dequeue();
var currentNode = FindNodeById(graphNodes, currentEdge.Source);
if (distances[currentNode.Id] < currentEdge.Distance) continue;
foreach (var neighborEdge in currentNode.Edges) {
var neighborDistance = currentEdge.Distance + neighborEdge.Distance;
var neighborNode = FindNodeById(graphNodes, neighborEdge.Target);
if (neighborDistance < distances[neighborNode.Id]) {
distances[neighborNode.Id] = neighborDistance;
unvisited.Enqueue(new Edge(neighborNode.Id, neighborDistance));
}
}
}
return distances;
}
private static Node FindNodeById(List<Node> nodes, int id) {
return nodes.FirstOrDefault(n => n.Id == id);
}
```
`PriorityQueue<Edge>` 是用来存储边的优先级队列,`dequeue()` 方法每次取出距离最小的边。`FindNodeById` 函数则是根据节点ID从列表中找到对应节点。
阅读全文