链式前向星dfs的c++代码
时间: 2024-10-05 17:03:56 浏览: 42
链式前向星(Dijkstra's Algorithm with Adjacency List)是一种图算法,用于寻找有向图或无向图中的最短路径。下面是使用C++实现的一个简单版本:
```cpp
#include <iostream>
#include <vector>
#include <queue>
#include <limits>
using namespace std;
struct Edge {
int destination;
int weight;
};
class Graph {
private:
vector<vector<Edge>> adjList; // 使用邻接列表表示图
public:
void addEdge(int src, int dest, int weight) {
adjList[src].push_back({dest, weight});
}
pair<int, int> dijkstra(int start) {
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq; // 小顶堆
vector<int> distance(start, numeric_limits<int>::max());
distance[start] = 0;
pq.push({distance[start], start});
while (!pq.empty()) {
int u = pq.top().second;
pq.pop();
for (const auto &edge : adjList[u]) {
int v = edge.destination;
int newWeight = distance[u] + edge.weight;
if (newWeight < distance[v]) {
distance[v] = newWeight;
pq.push({distance[v], v});
}
}
}
return {distance[start], start};
}
};
int main() {
Graph g;
// 添加边到图...
pair<int, int> result = g.dijkstra(0); // 从节点0开始搜索最短路径
cout << "Shortest path from node 0 is to node " << result.second << " with a distance of " << result.first << endl;
return 0;
}
```
在这个代码中,`Graph`类有一个邻接列表`adjList`来存储图的信息,`dijkstra`函数采用小顶堆实现优先队列,通过广度优先搜索找到起点到其他所有节点的最短距离。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pptx](https://img-home.csdnimg.cn/images/20241231044947.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)