视频链接:
// 邻接表 头插法 #include <iostream> #include <cstring> #include <algorithm> #include <vector> using namespace std; const int N = 510,M = 3000; int n,m,a,b,c; int h[N],e[M],w[M],ne[M],idx; void add(int a,int b,int c){//加边 e[++idx]=b,w[idx]=c, ne[idx]=h[a],h[a]=idx; } void dfs(int u){ //访问 printf("%d/n",u); for(int i=h[u];i;i=ne[i]){ int v = e[i], c = w[i]; dfs(v); } } int main(){ cin >> n >> m; for(int i=1; i<=m; i++){ cin>>a>>b>>c, add(a,b,c); } dfs(1); return 0; } // 邻接表 尾插法 #include <iostream> #include <cstring> #include <algorithm> #include <vector> using namespace std; const int N = 510,M = 3000; int n,m,a,b,c; vector<int> e[M],w[M]; void dfs(int u){ //访问 printf("%d/n",u); for(int i=0;i<e[u].size();i++){ int v = e[u][i], c = w[u][i]; dfs(v); } } int main(){ cin >> n >> m; for(int i=1;i<=m;i++){ //加边 cin>>a>>b>>c, e[a].push_back(b), w[a].push_back(c); } dfs(1); return 0; }
原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/245635.html