用C++实现代码:1、实现图的深度优先遍历和广度优先遍历 2、最短路径算法。最短路径算法的实现,编写算法获得带权有向图中从源点到其他各点的最短路径。
时间: 2024-02-18 08:02:33 浏览: 71
C++有向图的深度优先和广度优先遍历等13项基础操作(代码共700行,可运行无错误).rar
5星 · 资源好评率100%
好的,以下是完整的C++代码实现:
1. 图的深度优先遍历和广度优先遍历
```c++
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
// 图的深度优先遍历
void DFS(int v, vector<bool>& visited, vector<vector<int>>& adj_list) {
visited[v] = true;
cout << v << " ";
for (auto i : adj_list[v]) {
if (!visited[i]) {
DFS(i, visited, adj_list);
}
}
}
// 图的广度优先遍历
void BFS(int v, vector<bool>& visited, vector<vector<int>>& adj_list) {
queue<int> q;
visited[v] = true;
q.push(v);
while (!q.empty()) {
int curr = q.front();
cout << curr << " ";
q.pop();
for (auto i : adj_list[curr]) {
if (!visited[i]) {
visited[i] = true;
q.push(i);
}
}
}
}
int main() {
// 创建邻接表表示的图
int n, m;
cin >> n >> m;
vector<vector<int>> adj_list(n);
for (int i = 0; i < m; i++) {
int u, v;
cin >> u >> v;
adj_list[u].push_back(v);
adj_list[v].push_back(u);
}
// 深度优先遍历
vector<bool> visited(n, false);
for (int i = 0; i < n; i++) {
if (!visited[i]) {
DFS(i, visited, adj_list);
}
}
cout << endl;
// 广度优先遍历
visited.assign(n, false);
for (int i = 0; i < n; i++) {
if (!visited[i]) {
BFS(i, visited, adj_list);
}
}
cout << endl;
return 0;
}
```
2. 最短路径算法
```c++
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
// 带权有向图的Dijkstra算法
void Dijkstra(int src, vector<vector<pair<int, int>>>& adj_list, vector<int>& dist) {
int V = adj_list.size();
vector<bool> visited(V, false);
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
// 将源点加入到优先队列中
pq.push(make_pair(0, src));
dist[src] = 0;
while (!pq.empty()) {
int u = pq.top().second;
pq.pop();
if (visited[u]) {
continue;
}
visited[u] = true;
for (auto i : adj_list[u]) {
int v = i.first;
int weight = i.second;
if (dist[v] > dist[u] + weight) {
dist[v] = dist[u] + weight;
pq.push(make_pair(dist[v], v));
}
}
}
}
int main() {
// 创建邻接表表示的带权有向图
int n, m;
cin >> n >> m;
vector<vector<pair<int, int>>> adj_list(n);
for (int i = 0; i < m; i++) {
int u, v, w;
cin >> u >> v >> w;
adj_list[u].push_back(make_pair(v, w));
}
// 从源点开始求最短路径
int src;
cin >> src;
vector<int> dist(n, INT_MAX);
Dijkstra(src, adj_list, dist);
// 输出源点到各点的最短路径
for (int i = 0; i < n; i++) {
cout << "Distance from " << src << " to " << i << " is " << dist[i] << endl;
}
return 0;
}
```
阅读全文