DFS:
#include<bits/stdc++.h>
using namespace std;
const int N = 10010,M = 10010;
int n,m;//n表示的是点数 m表示的是边数
struct Node{
int id;
Node* next;
Node (int _id): id(_id),next(NULL) {}
}*head[N];//创建n个头指针
bool st[N];//判断重复
void add(int a,int b)//链式前向星
{
auto p=new Node(b);
p->next=head[a];
head[a]=p;
}
void dfs(int u)
{
st[u]=true;
printf("%d ",u);
for(auto p=head[u];p;p=p->next)
{
int j=p->id;
if(!st[j])
dfs(j);
}
}
int main()
{
scanf("%d %d",&n,&m);
while(m--)
{
int a,b;//连接的两条边
scanf("%d %d",&a,&b);
add(a,b);
}
for(int i=1;i<=n;i++)//防止不连通图
{
if(!st[i])
dfs(i);
}
return 0;
}
BFS:
宽度遍历要借助于队列
#include<bits/stdc++.h>
using namespace std;
const int N = 10010,M = 10010;
int n,m;//n表示的是点数 m表示的是边数
struct Node{
int id;
Node* next;
Node (int _id): id(_id),next(NULL) {}
}*head[N];//创建n个头指针
bool st[N];//判断重复
void add(int a,int b)//链式前向星
{
auto p=new Node(b);
p->next=head[a];
head[a]=p;
}
void bfs()
{
queue<int> q;
q.push(1);
st[1]=true;
while(q.size())
{
auto t = q.front();
q.pop();
printf("%d ",t);
for(auto p=head[t];p;p=p->next)
{
int j=p->id;
if(!st[j])
{
st[j]=true;
q.push(j);
}
}
}
}
int main()
{
scanf("%d %d",&n,&m);
while(m--)
{
int a,b;//连接的两条边
scanf("%d %d",&a,&b);
add(a,b);
}
bfs();//广度优先遍历很少考虑不连通
return 0;
}