手机
当前位置:查字典教程网 >编程开发 >C语言 >判断给定的图是不是有向无环图实例代码
判断给定的图是不是有向无环图实例代码
摘要:复制代码代码如下:#include#include#includeusingnamespacestd;classGraph{intverte...

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

复制代码 代码如下:

#include<iostream>

#include<list>

#include<stack>

using namespace std;

class Graph {

int vertexNum;

list<int> *adjacents;

public:

Graph(int _vertexNum) {

vertexNum = _vertexNum;

adjacents = new list<int>[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<int>::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<int> 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<int>::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;

}

【判断给定的图是不是有向无环图实例代码】相关文章:

求子数组最大和的实例代码

基于C中一个行压缩图的简单实现代码

判断机器大小端的两种实现方法

Linux C 获取进程退出值的实现代码

c++ 巧开平方的实现代码

C++多继承同名隐藏实例详细介绍

C++求斐波那契数的实例代码

linux c多线程编程实例代码

Qt实现图片移动实例(图文教程)

贪心算法 WOODEN STICKS 实例代码

精品推荐
分类导航