可以有5个类型
- 邻接矩阵
- 边集数组
- 邻接表
- 链式邻接表
- 链式前向星
邻接矩阵
#include#include using namespace std; #define N 99 int n,m; bool vis[N]; int w[N][N]; void dfs(int u) { vis[u] = true; for(int v = 1; v <= n; ++v) { if (w[u][v]){ cout << u <<"->"<< v <<":" << w[u][v] << endl; if (vis[v]) continue; dfs(v); } } } int main() { int a, b, c; cout << "the number of vertex and edges:" << endl; cin >> n >> m; cout< > a >> b >> c; w[a][b] = c; } dfs(1); return 0; }
边集数组
#include#include using namespace std; #define N 99 #define M 99 struct edge{ int u, v, w; }e[M]; int n, m; int vis[N]; void dfs(int u) { vis[u] = true; for(int i = 1; i <= n; ++i) { if (e[i].u == u){ // i 表示输入配对的顶点和边的编号。 int v = e[i].v, w = e[i].w; cout << u <<"->"<< v <<":" << w << endl; if (vis[v]) continue; dfs(e[i].v); } } } int main() { int a, b, c; cout << "the number of vertex and edges:" << endl; cin >> n >> m; cout< > a >> b >> c; e[i] = {a, b, c}; } dfs(1); return 0; }
邻接表
#include#include using namespace std; #define N 99 struct edge{ int v, w; }; vector e[N]; int n, m; void dfs(int u, int fa) { for(auto ed : e[u]) { int v = ed.v, w = ed.w; if (v == fa) continue; //fa记录的是u的前向顶点 cout << u <<"->"<< v <<":" << w << endl; dfs(v, u); } } int main() { int a, b, c; cout << "the number of vertex and edges:" << endl; cin >> n >> m; cout< > a >> b >> c; e[a].push_back({b,c}); e[b].push_back({a,c}); } cout << "result:" << endl; dfs(1, 0); return 0; }
链式邻接表
#include#include #include #include using namespace std; const int N=510; int n,m,a,b,c; struct edge{int u,v,w;}; vector e;//边集 vector h[N];//二维数组,表示点的所有出边 void add(int a, int b, int c) { e.push_back({a, b, c}); h[a].push_back(e.size() - 1); // h[a]的下标代表顶点,h[a]存编号 } void dfs(int u, int fa) { for(int i = 0; i < h[u].size(); ++i) { int j = h[u][i]; // 存储u点所有出边的编号 int v = e[j].v, w = e[j].w; if (v == fa) continue; //fa记录的是u的前向顶点 cout << u <<"->"<< v <<":" << w << endl; dfs(v, u); } } int main() { cout << "the number of vertex and edges:" << endl; cin >> n >> m; cout< > a >> b >> c; add(a, b, c); add(b, a, c); } cout << "result:" << endl; dfs(1, 0); return 0; }
链式前向星
#include#include #include #include using namespace std; const int N=510, M= 3000; int n,m,a,b,c; struct edge{int v,w,ne;}; //e[i]表示第i条出边的{终点v, 边权w, 下一条边ne} edge e[M]; //边集 int idx,h[N]; //点的第一条出边 void add(int a, int b, int c) { e[idx] = {b, c, h[a]}; h[a] = idx++; } void dfs(int u, int fa) { for(int i = h[u]; ~ i; i = e[i].ne) { int v = e[i].v, w = e[i].w; if (v == fa) continue; //fa记录的是u的前向顶点 cout << u <<"->"<< v <<":" << w << endl; dfs(v, u); } } int main() { cout << "the number of vertex and edges:" << endl; cin >> n >> m; memset(h, -1, sizeof h); cout< > a >> b >> c; add(a, b, c); add(b, a, c); } cout << "result:" << endl; dfs(1, 0); return 0; }



