vector邻接表建图+DFS+BFS
生活随笔
收集整理的這篇文章主要介紹了
vector邻接表建图+DFS+BFS
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
以邊操作為主的圖用邊集數組存儲比較好,相比鏈式前向星,vector建圖更容易懂。
#include <iostream> #include <cstdio> #include <cstring> #include <vector> #include <queue> using namespace std; using LL = long long; const int inf = 0x3f3f3f3f; const int MAX_E = 1e5+5; // 最大邊數 const int MAX_V = 1e4+5; // 最大節點數 int V, E; // 點、邊 struct edge{ int to, w; }; vector<edge> G[MAX_E]; bool vis[MAX_V];void input(); void Build(int x, int y, int w); void _dfs(int s); void dfs(int s); // 封裝了memset void bfs(int s);int main() {input();dfs(0);cout << endl;bfs(0);return 0; }void Build(int x, int y, int w = 1) {edge e; e.to = y; e.w = w;G[x].push_back(e); }void input() {int a,b,w;edge e;cin >> V >> E;for (int i = 0; i < E; i++){cin >> a >> b >> w; // 帶權//cin >> a >> b; // 不帶權Build(a, b);Build(b, a); // 無向} }void _dfs(int s) {vis[s] = true;cout << s << endl;for (int i = 0; i < G[s].size(); i++){if (!vis[G[s][i].to]) _dfs(G[s][i].to);} }void dfs(int s) {memset(vis, false, sizeof(vis)); // 這步不能遞歸,所以封裝起來了_dfs(s); }void bfs(int s) {memset(vis, false, sizeof(vis)); // 此處vis的含義是節點是否在隊列中queue<int> Q;Q.push(s);while (!Q.empty()){s = Q.front();Q.pop();cout << s << endl; // 出隊,執行操作vis[s] = true;for (int i = 0; i < G[s].size(); i++) {if (!vis[G[s][i].to]) {Q.push(G[s][i].to);vis[G[s][i].to] = true;}}} }樣例輸入
從嚴老師書上借了張圖,當無向圖用了
輸出
0 2 1 3 5 40 2 4 5 1 3總結
以上是生活随笔為你收集整理的vector邻接表建图+DFS+BFS的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++ priority_queue用法
- 下一篇: vector邻接表建图+dijkstra