用邻接表存,为了方便依旧是输入的v代表该点是第几个点。然后输出的是从该点进行DFS的遍历的点的顺序。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
| #include <bits/stdc++.h> using namespace std; typedef struct Arcnode{ int vertex,data; struct Arcnode *nextArc; }Arcnode; typedef struct vernode{ int data; Arcnode *nextArc; }vernode; typedef struct { vernode vertex[1001]; int vernum,arcnum; }Graph; int vis[1001]; int locate(Graph G, int x) { for(int i = 1 ; i <= G.vernum; ++i) { if(G.vertex[i].data == x) { return i; } } } void create(Graph &G) { int a,b,w; cin >> G.vernum >> G.arcnum; for(int i = 1; i <= G.vernum ; ++i) { cin >> G.vertex[i].data; G.vertex[i].nextArc = NULL; } for(int i = 1; i <= G.arcnum; ++i) { cin >> a >> b >> w; int A = locate(G,a); int B = locate(G,b); Arcnode *p,*p1; p = new Arcnode; p -> vertex = B; p -> nextArc = G.vertex[A].nextArc; p -> data = w; G.vertex[A].nextArc = p; p = new Arcnode; p -> vertex = A; p -> nextArc = G.vertex[B].nextArc; p -> data = w; G.vertex[B].nextArc = p; } } void dfs(Graph G,int v) { vis[v] = 1; cout << v << '\n'; Arcnode *p; p = G.vertex[v].nextArc; while(p != NULL) { int index = p -> vertex; if(!vis[index]) { vis[index] = 1; dfs(G,index); } p = p -> nextArc; } } int main() { memset(vis,0,sizeof(vis)); Graph G; create(G); int v; cin >> v; dfs(G,v); }
|