核心是深度优先算法遍历到已访问过的节点是即可判定是否是有向无环图。存储的结构是用链表做的。
#include <iostream>
using namespace std;
bool visited[100] = { false };
bool ans = true;
class Node;
class Edge
{
public:
Edge()
{
to = nullptr;
next = nullptr;
}
Node* to;
Edge* next;
};
class Node
{
public:
Node(int a = 0)
{
data = 0;
next = nullptr;
}
Edge* next;
int data;
};
void Travel(Node G)
{
if (ans)
{
if (visited[G.data])
{
ans = false;
return;
}
visited[G.data] = true;
Edge* p = G.next;
if (p != nullptr)
{
Travel(*(p->to));
}
return;
}
}
int main()
{
int n, m;
cin >> n >> m;
Node* Graph = new Node[n+1];
for (int i = 0; i <= n ; i++)
{
Graph[i].data = i;
}
for (int i = 0; i <= m - 1; i++)
{
int u, v;
cin >> u >> v;
if (Graph[u].next == nullptr)
{
Graph[u].next = new Edge;
Graph[u].next->to = &Graph[v];
}
else
{
Edge* p = Graph[u].next;
while (p->next != nullptr)
{
p = p->next;
}
p->next = new Edge;
p->next->to = &Graph[v];
}
}
Travel(Graph[1]);
cout << ans << endl;
}