码迷,mamicode.com
首页 > 编程语言 > 详细

每日一算法之拓扑排序

时间:2015-07-16 00:42:32      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:

伪代码:

TopLogical(G)
    call DFS to compute finishtime
    as each vertex finished , insert it onto the front of a linked list
  return the linked list of vertices

  

实现如下:

#include <iostream>
#include <vector>
#include <memory>
using namespace std;
vector<vector<int>> graphic;
vector<int> res;
bool *visit;
int length;
void init()
{
	visit = new bool[length];
	cout<<"init:"<<length<<endl;
	for(int i = 0 ; i < length ; ++i)
	{
		visit[i] = false;
	}
}
void Dfs(int cur)
{
	if(visit[cur] )
	{
		return ;
	}
	visit[cur] = true;
	for(int i = 0 ; i < graphic[cur].size() ; ++i)
	{
	
		Dfs(graphic[cur][i]);
	}
	cout<<"dfs:"<<cur<<endl;
	res.push_back(cur);
}
///void SecondDfs()
//{

//}
int main()
{
	length = 7;
	vector<int> ve;
	init();
	for(int i = 0 ; i < length ; ++i)
	{
		graphic.push_back(ve);
	}
	graphic[0].push_back(1);
	graphic[0].push_back(3);
	graphic[1].push_back(2);
	graphic[1].push_back(3);
	graphic[2].push_back(6);
	graphic[4].push_back(2);
	graphic[4].push_back(5);
	graphic[5].push_back(6);
	for(int i = 0 ; i < length ; ++i)
	{
		Dfs(i);
	}
	for(int i = res.size()-1 ; i >= 0; --i)
	{
		cout<<res[i]<<" ";
	}


	return 0;
}

  

每日一算法之拓扑排序

标签:

原文地址:http://www.cnblogs.com/fengyuehan/p/4649702.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!