DirectedCycle API
DirectedCycle(Digraph G)
寻找有向环的构造函数
bool hasCycle()
G中是否含有有向环
stack<int> cycle()
有向环中的所有顶点(如果存在的话)
图解
代码
#pragma once
#include<stack>
#include"Digraph.h"
class DirectedCycle
{
public:
DirectedCycle(Digraph& G);
bool hasCycle() {
return m_cycle != nullptr;
}
stack<int>* cycle() {
return m_cycle;
}
private:
vector<bool>* m_marked = nullptr;
vector<int>* m_father = nullptr;
vector<bool>* m_onStack = nullptr;
stack<int>* m_cycle = nullptr;
void dfs(Digraph& G, int v);
};
void testDirectedCycle();
#include "DirectedCycle.h"
DirectedCycle::DirectedCycle(Digraph& G)
{
int n = G.V();
m_marked = new vector<bool>(n, false);
m_father = new vector<int>(n, -1);
m_onStack = new vector<bool>(n, false);
for (int i = 0; i < n; ++i) {
if (!m_marked->at(i)) {
dfs(G, i);
}
}
}
void DirectedCycle::dfs(Digraph& G, int v)
{
m_onStack->at(v) = true;
m_marked->at(v) = true;
forIt(G.adj(v)) {
if(this->hasCycle()) return;
if(!m_marked->at(*it)) {
m_father->at(*it) = v;
dfs(G, *it);
}else if(m_onStack->at(*it)){
m_cycle = new stack<int>();
for (int i = v; i != *it; i=m_father->at(i)) {
m_cycle->push(i);
}
m_cycle->push(*it);
m_cycle->push(v);
}
}
m_onStack->at(v) = false;
}
void testDirectedCycle()
{
Digraph G("tinyDG.txt");
DirectedCycle DC(G);
out(DC.hasCycle()),hh;
Digraph G1("tinyDAG.txt");
DirectedCycle DC2(G1);
out(DC2.hasCycle()), hh;
}
tinyDAG.txt
13
15
2 3
0 6
0 1
2 0
11 12
9 12
9 10
9 11
3 5
8 7
5 4
0 5
6 4
6 9
7 6