清醒时做事,糊涂时读书,大怒时睡觉,无聊时关注图老师为大家准备的精彩内容。下面为大家推荐判断给定的图是不是有向无环图实例代码,无聊中的都看过来。
【 tulaoshi.com - 编程语言 】
代码如下:
#includeiostream
#includelist
#includestack
using namespace std;
class Graph {
int vertexNum;
listint *adjacents;
public:
Graph(int _vertexNum) {
vertexNum = _vertexNum;
adjacents = new listint[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;
listint::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;
stackint 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 (listint::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;
}
来源:http://www.tulaoshi.com/n/20160219/1589487.html
看过《判断给定的图是不是有向无环图实例代码》的人还看了以下文章 更多>>