#include <iostream> #include <vector> #include <queue> using namespace std; // 定义图的边结构体 struct Edge { int to; // 边的终点 int weight; // 边的权重 Edge(int t, int w) : to(t), weight(w) {} }; // 定义图的邻接表结构体 struct Graph { int n; // 节点数 vector<vector<Edge>> adj; // 邻接表 Graph(int n) : n(n), adj(n) {} // 添加一条边 void addEdge(int from, int to, int weight) { adj[from].push_back(Edge(to, weight)); } // 深度优先遍历 void dfs(int cur, vector<bool>& visited) { visited[cur] = true; cout << cur << " "; for (auto e : adj[cur]) { if (!visited[e.to]) { dfs(e.to, visited); } } } // 广度优先遍历 void bfs(int cur, vector<bool>& visited) { queue<int> q; q.push(cur); visited[cur] = true; while (!q.empty()) { int u = q.front(); q.pop(); cout << u << " "; for (auto e : adj[u]) { if (!visited[e.to]) { visited[e.to] = true; q.push(e.to); } } } } }; int main() { int n, m; cin >> n >> m; Graph g(n); for (int i = 0; i < m; i++) { int u, v, w; cin >> u >> v >> w; g.addEdge(u, v, w); g.addEdge(v, u, w); // 无向图需要添加反向边 } // 深度优先遍历 cout << "DFS: "; vector<bool> visited(n, false); g.dfs(0, visited); cout << endl; // 广度优先遍历 cout << "BFS: "; visited.assign(n, false); g.bfs(0, visited); cout << endl; return 0; }给代码添加注释
时间: 2024-02-14 20:10:47 浏览: 22
```
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
// 定义图的边结构体
struct Edge {
int to; // 边的终点
int weight; // 边的权重
Edge(int t, int w) : to(t), weight(w) {} // 构造函数
};
// 定义图的邻接表结构体
struct Graph {
int n; // 节点数
vector<vector<Edge>> adj; // 邻接表
Graph(int n) : n(n), adj(n) {} // 构造函数
// 添加一条边
void addEdge(int from, int to, int weight) {
adj[from].push_back(Edge(to, weight));
}
// 深度优先遍历
void dfs(int cur, vector<bool>& visited) {
visited[cur] = true;
cout << cur << " ";
for (auto e : adj[cur]) {
if (!visited[e.to]) {
dfs(e.to, visited);
}
}
}
// 广度优先遍历
void bfs(int cur, vector<bool>& visited) {
queue<int> q;
q.push(cur);
visited[cur] = true;
while (!q.empty()) {
int u = q.front();
q.pop();
cout << u << " ";
for (auto e : adj[u]) {
if (!visited[e.to]) {
visited[e.to] = true;
q.push(e.to);
}
}
}
}
};
int main() {
int n, m;
cin >> n >> m;
Graph g(n);
for (int i = 0; i < m; i++) {
int u, v, w;
cin >> u >> v >> w;
g.addEdge(u, v, w);
g.addEdge(v, u, w); // 无向图需要添加反向边
}
// 深度优先遍历
cout << "DFS: ";
vector<bool> visited(n, false);
g.dfs(0, visited);
cout << endl;
// 广度优先遍历
cout << "BFS: ";
visited.assign(n, false);
g.bfs(0, visited);
cout << endl;
return 0;
}
```
注释已添加在代码中。