用C++实现代码:1、实现图的深度优先遍历和广度优先遍历 2、最短路径算法。最短路径算法的实现,编写算法获得带权有向图中从源点到其他各点的最短路径。
时间: 2024-02-18 21:02:40 浏览: 49
C++实现的一些算法
下面是用C++实现图的深度优先遍历和广度优先遍历的代码:
```c++
#include <iostream>
#include <vector>
#include <queue>
#include <stack>
using namespace std;
class Graph {
public:
Graph(int n) {
this->n = n;
adj.resize(n);
}
void addEdge(int u, int v) {
adj[u].push_back(v);
}
void dfs(int s) {
vector<bool> visited(n, false);
dfsUtil(s, visited);
}
void bfs(int s) {
vector<bool> visited(n, false);
queue<int> q;
visited[s] = true;
q.push(s);
while (!q.empty()) {
int u = q.front();
q.pop();
cout << u << " ";
for (int i = 0; i < adj[u].size(); i++) {
int v = adj[u][i];
if (!visited[v]) {
visited[v] = true;
q.push(v);
}
}
}
}
private:
int n;
vector<vector<int>> adj;
void dfsUtil(int u, vector<bool>& visited) {
visited[u] = true;
cout << u << " ";
for (int i = 0; i < adj[u].size(); i++) {
int v = adj[u][i];
if (!visited[v]) {
dfsUtil(v, visited);
}
}
}
};
int main() {
Graph g(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);
cout << "DFS starting from vertex 2: ";
g.dfs(2);
cout << endl;
cout << "BFS starting from vertex 2: ";
g.bfs(2);
cout << endl;
return 0;
}
```
下面是用C++实现最短路径算法的代码:
```c++
#include <iostream>
#include <vector>
#include <queue>
#include <limits.h>
using namespace std;
#define INF INT_MAX
class Graph {
public:
Graph(int n) {
this->n = n;
adj.resize(n);
}
void addEdge(int u, int v, int w) {
adj[u].push_back(make_pair(v, w));
}
void shortestPath(int s) {
vector<int> dist(n, INF);
dist[s] = 0;
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
pq.push(make_pair(0, s));
while (!pq.empty()) {
int u = pq.top().second;
pq.pop();
for (int i = 0; i < adj[u].size(); i++) {
int v = adj[u][i].first;
int w = adj[u][i].second;
if (dist[v] > dist[u] + w) {
dist[v] = dist[u] + w;
pq.push(make_pair(dist[v], v));
}
}
}
cout << "Shortest distances from source vertex: " << endl;
for (int i = 0; i < n; i++) {
cout << s << " -> " << i << " = " << dist[i] << endl;
}
}
private:
int n;
vector<vector<pair<int, int>>> adj;
};
int main() {
Graph g(5);
g.addEdge(0, 1, 10);
g.addEdge(0, 4, 5);
g.addEdge(1, 2, 1);
g.addEdge(1, 4, 2);
g.addEdge(2, 3, 4);
g.addEdge(3, 2, 6);
g.addEdge(3, 0, 7);
g.addEdge(4, 1, 3);
g.addEdge(4, 2, 9);
g.addEdge(4, 3, 2);
g.shortestPath(0);
return 0;
}
```
阅读全文