数组模拟存图
gb_lw
·
·
个人记录
#include<bits/stdc++.h>
using namespace std;
int n,m,u,y,v[100005],h[100005],vtx[100005],ntx[100005],idx=1;
void adde(int u,int v){
vtx[idx]=v;
ntx[idx]=h[u];
h[u]=idx++;
}
void dfs(int x){
v[x]=1;
cout<<x<<' ';
int it=h[x];
while(it!=-1){
if(!v[vtx[it]]){
dfs(vtx[it]);
}
it=ntx[it];
}
}
void bfs(){
queue<int> q;
q.push(1);
v[1]=1;
while(!q.empty()){
int x=q.front();
cout<<x<<' ';
q.pop();
int it=h[x];
while(it!=-1){
if(!v[vtx[it]]){
v[vtx[it]]=1;
q.push(vtx[it]);
}
it=ntx[it];
}
}
}
int main(){
cin>>n>>m;
memset(h,-1,sizeof(h));
for(int i=1;i<=m;i++){
cin>>u>>y;
adde(u,y);
}
dfs(1);
cout<<endl;
memset(v,0,sizeof(v));
bfs();
return 0;
}