图
作者:
Spark_10
,
2024-12-05 20:51:12
,
所有人可见
,
阅读 1
dfs
#include <iostream>
#include <cstring>
using namespace std;
const int N = 510;
int g[N][N];
bool st[N];
struct Node
{
int id;
Node* next;
Node(int _id) : id(_id), next(NULL) {}
}* head[N];
void add(int a, int b)
{
Node* p = new Node(b);
p->next = head[a];
head[a] = p;
“············”
g[a][b] = 1;
}
void dfs(int u) //邻接表
{
st[u] = true;
cout << u << ' ';
for (Node* p = head[u]; p; p = p->next)
if (!st[p->id])
dfs(p->id);
}
void dfs2(int u) //邻接矩阵
{
st[u] = true;
cout<<u<<' ';
for(int i=u; i<=n; i++)
{
if(g[u][i]==1&&st[i]==false)
dfs(i);
}
}
int main()
{
int n, m;
cin >> n >> m;
while (m -- )
{
int a, b;
cin >> a >> b;
add(a, b);
// g[a][b] = w;
}
for (int i = 1; i <= n; i ++)
if (!st[i])
dfs(i);
return 0;
}