判斷給定的圖是不是有向無環(huán)圖實(shí)例代碼

#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;
}
相關(guān)文章
C語言實(shí)現(xiàn)基于最大堆和最小堆的堆排序算法示例
這篇文章主要介紹了C語言實(shí)現(xiàn)基于最大堆和最小堆的堆排序算法示例,分別是基于最大堆的升序排序和基于最小堆的降序排序?qū)嵗?需要的朋友可以參考下2016-06-06
Qt使用SQLite數(shù)據(jù)庫存儲(chǔ)管理圖片文件
這篇文章主要為大家詳細(xì)介紹了Qt如何使用SQLite數(shù)據(jù)庫實(shí)現(xiàn)存儲(chǔ)管理圖片文件的功能,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解一下2023-04-04
C++實(shí)現(xiàn)的分布式游戲服務(wù)端引擎KBEngine詳解
這篇文章主要詳細(xì)介紹了C++實(shí)現(xiàn)的分布式游戲服務(wù)端引擎KBEngine的概念以及使用方法,非常的實(shí)用,有需要的小伙伴可以參考下2015-03-03
純c實(shí)現(xiàn)異常捕獲try-catch組件教程示例
這篇文章主要為大家介紹了純c實(shí)現(xiàn)異常捕獲try-catch組件教程示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-08-08
C語言 function recursion函數(shù)遞歸詳解
遞歸指的是在函數(shù)的定義中使用函數(shù)自身的方法,舉個(gè)例子: 從前有座山,山里有座廟,廟里有個(gè)老和尚,正在給小和尚講故事呢!故事是什么呢?"從前有座山,山里有座廟,廟里有個(gè)老和尚,正在給小和尚講故事呢!故事是什么呢?"從前有座山,山里有座廟,循環(huán)下去2021-10-10
探討編寫int strlen(char *strDest);不允許定義變量的問題
本篇文章是對(duì)編寫int strlen(char *strDest);不允許定義變量的問題進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05
C++實(shí)現(xiàn)簡(jiǎn)單FTP客戶端軟件開發(fā)
這篇文章主要為大家詳細(xì)介紹了C++實(shí)現(xiàn)簡(jiǎn)單FTP客戶端軟件開發(fā),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-08-08

