图的DFS、BFS模板-邻接表存储
作者:
acwingcyc
,
2022-10-03 15:57:26
,
所有人可见
,
阅读 260
图的DFS模板-邻接表存储
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 100010;
int n,m;
struct Node {
int id;
Node* next;
Node(int _id):id(_id),next(NULL) {}
} *head[N];
void add(int a,int b) {
auto p = new Node(b);
p->next = head[a];
head[a] = p;
}
bool st[N];
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()
{
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 <cstring>
#include <algorithm>
#include <queue>
using namespace std;
const int N = 100010;
int n,m;
struct Node {
int id;
Node* next;
Node(int _id):id(_id),next(NULL) {}
} *head[N];
void add(int a,int b) {
auto p = new Node(b);
p->next = head[a];
head[a] = p;
}
bool st[N];
void bfs(int u) {
queue<int> q;
q.push(u);
st[u] = 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]) {
q.push(j);
st[j] = true;
}
}
}
}
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]) bfs(i);
return 0;
}