判断图有无环_判断给定的图是不是有向无环图实例代码

#include

#include

#include

using namespace std;

class Graph {

int vertexNum;

list *adjacents;

public:

Graph(int _vertexNum) {

vertexNum = _vertexNum;

adjacents = new list[vertexNum];

}

void findIndegree(int *indegree, int n);

bool topologicalSort();

void addEdge(int v, int w);

};

void Graph::addEdge(int v, int w) {

adjacents[v].push_back(w);

}

void Graph::findIndegree(int *indegree, int n) {

int v;

list::iterator iter;

for(v = 0; v < vertexNum; v++) {

for (iter = adjacents[v].begin(); iter != adjacents[v].end(); iter++)

indegree[*iter]++;

}

}

bool Graph::topologicalSort() {

int ver_count = 0;

stack m_stack;

int *indegree = new int[vertexNum];

memset(indegree, 0, sizeof(int) * vertexNum);

findIndegree(indegree, vertexNum);

int v;

for (v = 0; v < vertexNum; v++)

if (0 == indegree[v])

m_stack.push(v);

while (!m_stack.empty()) {

v = m_stack.top();

m_stack.pop();

cout << v << " ";

ver_count++;

for (list::iterator iter = adjacents[v].begin(); iter != adjacents[v].end(); iter++) {

if (0 == --indegree[*iter])

m_stack.push(*iter);

}

}

cout << endl;

if (ver_count < vertexNum)

return false;

return true;

}

int main(int argc, char *argv[]) {

Graph g(6);

g.addEdge(5, 2);

g.addEdge(5, 0);

g.addEdge(4, 0);

g.addEdge(4, 1);

g.addEdge(2, 3);

g.addEdge(3, 1);

if (g.topologicalSort())

cout << "it is a topological graph" << endl;

else

cout << "it is not a topological graph" << endl;

cin.get();

return 0;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值