图的遍历
作者:
zzu
,
2024-05-07 21:48:45
,
所有人可见
,
阅读 3
DFS
#include <iostream>
using namespace std;
const int N = 100010, M = 100010;
int n, m;
struct Node
{
int id;
Node* next;
Node(int _id): id(_id), next(NULL){}
}*head[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;
cout << u << " ";
for(auto q = head[u]; q; q = q->next)
{
int j = q->id;
if(!st[j]) dfs(j);
}
}
int main()
{
cin >> n >> m;
while(m --)
{
int a, b;
cin >> a >> b;
add(a, b);
}
for(int i = 1; i <= n; i ++)
if(!st[i]) dfs(i);
return 0;
}
BFS
#include <iostream>
#include <queue>
using namespace std;
const int N = 100010, M = 100010;
int n, m;
struct Node
{
int id;
Node* next;
Node(int _id): id(_id), next(NULL){}
}*head[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();
cout << 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()
{
cin >> n >> m;
while(m --)
{
int a, b;
cin >> a >> b;
add(a, b);
}
bfs();
return 0;
}