直接上代码
链式前向星
#include <cstdio>
#include <cstring>
#include <vector>
#include <iostream>
using namespace std;
int n,m;
const int N = 2000000;
int head[N];
struct node
{
int u,v,w,nex;
};
vector <node> vec;
void addEdge(int x,int y,int z)
{
vec.push_back({x,y,z,head[x]});
head[x] = vec.size() - 1;//垫刀要减1
}
void dfs(int p)
{
/*遍历*/
int i;
printf("%d ",p);
for(i=head[p];i!=-1;i=vec[i].nex)
{
dfs(vec[i].v);
}
}
int main()
{
register int i,j;
cin>>n>>m;
memset(head,-1,sizeof(head));
vec.clear();
vec.push_back({0,0,0,0});//垫一下
for(i=1;i<=m;i++)
{
int x,y,z;
cin>>x>>y>>z;
addEdge(x,y,z);
}
dfs(1);//从一号点遍历
return 0;
}
邻接表的创立(list)
#include <cstdio>
#include <list>
#include <vector>
#include <queue>
#include <iostream>
using namespace std;
int n,m;
list <int> *adj;
vector <int> ans;
bool *vis;
void addEdge(int x,int y)
{
adj[x].push_back(y);
}
void dfs(int p)
{
int i;
list <int>::iterator it;
vis[p] = 1;
for(it=adj[p].begin();it!=adj[p].end();it++)
{
if(!vis[*it])dfs(*it);
}
}
int main()
{
register int i,j;
int T;
cin>>T;
while(T--)
{
scanf("%d",&n);
scanf("%d",&m);
ans.clear();
adj = new list <int>[n+1];
vis = new bool[n+1];
for(i=1;i<=m;i++)
{
int x,y;
cin>>x>>y;
addEdge(x,y);
}
dfs(1);
delete [] adj;
delete [] vis;
}
return 0;
}
后记
邻接表也可以用vector vec[N]这种方法实现,加入operator还可以进行排序