图论Graph Theory(5):拓扑排序

1. 什么是拓扑排序

拓扑排序是对有向无环图 DAG 中的所有节点的一种线性次序,满足如下条件:对于每一条有向边 uv,拓扑排序中,节点 u 总会出现在节点 v 之前,拓扑排序只能用于 DAG
在这里插入图片描述

例如{5,4,2,3,1,0}就是一种拓扑排序,当然拓扑排序也不是唯一,{4,5,2,3,1,0}也是一种拓扑排序。

2. 拓扑排序与 DFS 遍历的区别

与拓扑排序不同,DFS 的结果为{5,2,3,1,0,4}

3. 拓扑排序的实现

#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <queue>
#include <vector>
#include <stack>
#include <list>
using namespace std;

class Graph {
	// the number of vertices
	int V;

	// contain adjacency vertices
	list<int>* adj;

	// A function used by TopologicalSort
	void TopologicalOrder(int v,bool isvisited[],stack<int>& Stack);
public:
	// Constructor
	Graph(int V);

	// A function to add an edge to graph
	void addEdge(int v,int w);

	// A TopologicalSort of DAG
	void TopologicalSort();
};

Graph:: Graph(int v)
{
	this->V = v;
	adj = new list<int>[v];
}

void Graph::addEdge(int v,int u)
{
	adj[v].push_back(u);
}

void Graph::TopologicalOrder(int v,bool isvisited[],
							 stack<int>& Stack)
{
	// Mark the current nodes as visited
	isvisited[v] = true;

	// Recur for all the vertices
	// adjacent to this vertex
	list<int>::iterator iter;
	for(iter = adj[v].begin();iter != adj[v].end();iter++)
		if(!isvisited[*iter])
			TopologicalOrder(*iter,isvisited,Stack);

	// Push current vertex to stack
	// which stores result
	Stack.push(v);
}

// This function to do Topological Sort.
// It uses recursive TopologicalOrder()
void Graph::TopologicalSort()
{
	stack<int>Stack;

	// Mark all the vertices as not visited
	bool isvisited[V];
	for(int i = 0;i < V;i++) 
		isvisited[i] = false;

	for(int i = 0;i < V;i++) 
		if(!isvisited[i])
			TopologicalOrder(i,isvisited,Stack);

	// Print contents of stack
	while(!Stack.empty()) {
		cout<< Stack.top()<<" ";
		Stack.pop();
	}
}
int main()
{
	// Create a graph
	Graph graph(6);
	graph.addEdge(5,2);
	graph.addEdge(5,0);
	graph.addEdge(4,0);
	graph.addEdge(4,1);
	graph.addEdge(2,3);
	graph.addEdge(3,1);

	cout<<"Following is a Topological Sort of the given graph"<<endl;

	graph.TopologicalSort();

	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值