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

所属分类: 软件编程 / C 语言 阅读数: 103
收藏 0 赞 0 分享

复制代码 代码如下:

#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++中变量类型的深入分析

本篇文章是对c++中的变量类型进行了详细的分析介绍。需要的朋友参考下
收藏 0 赞 0 分享

从汇编看c++的默认析构函数的使用详解

本篇文章是对c++中默认析构函数的使用进行了详细的分析介绍。需要的朋友参考下
收藏 0 赞 0 分享

基于c++中的默认拷贝函数的使用详解

本篇文章对c++中默认拷贝函数的使用进行了详细的分析介绍。需要的朋友参考下
收藏 0 赞 0 分享

解析c++中的默认operator=操作的详解

本篇文章是对c++中的默认operator=操作的应用进行了详细的分析介绍。需要的朋友参考下
收藏 0 赞 0 分享

解析c++中参数对象与局部对象的析构顺序的详解

本篇文章是对c++中参数对象与局部对象的析构顺序进行了详细的分析介绍,需要的朋友参考下
收藏 0 赞 0 分享

深入c++中临时对象的析构时机的详解

本篇文章对c++中临时对象的析构时机进行了详细的分析介绍,需要的朋友参考下
收藏 0 赞 0 分享

解析内存对齐 Data alignment: Straighten up and fly right的详解

对于所有直接操作内存的程序员来说,数据对齐都是很重要的问题.数据对齐对你的程序的表现甚至能否正常运行都会产生影响
收藏 0 赞 0 分享

深入内存对齐的详解

本篇文章是对内存对齐进行了详细的分析介绍,需要的朋友参考下
收藏 0 赞 0 分享

深入C语言把文件读入字符串以及将字符串写入文件的解决方法

本篇文章是对C语言把文件读入字符串以及将字符串写入文件的方法进行了详细的分析介绍,需要的朋友参考下
收藏 0 赞 0 分享

深入Windows下的回车是回车换行(\r\n)还是换行回车(\n\r)的详解

本篇文章对Windows下的回车是回车换行(\r\n)还是换行回车(\n\r)进行了详细的分析介绍,需要的朋友参考下
收藏 0 赞 0 分享
查看更多