有向无环图的深度优先搜索的逆后续,就是图的拓扑排序顺序
1 数据结构如下
2 3 0
0 6 00 1 0
2 0 0
11 12 0
9 12 0
9 10 0
9 11 0
3 5 0
8 7 0
5 4 0
0 5 0
6 4 0
6 9 0
7 6 0
2 C++代码如下
/*
* Topological.h
*
* Created on: 2014年6月3日
* Author: zhongchao
*/
#ifndef _TOPOLOGICAL_
#define _TOPOLOGICAL_
#include "DirWeightGraph.h"
class Topological
{
private:
bool* mark;
int* edgeTo;
vector<int> pre; //前序
vector<int> last; //后序
vector<int> reLast; //逆后续
public:
Topological(DirWeightGraph* graph, int n);
~Topological();
void dfs(DirWeightGraph* graph, int n);
vector<int> order();
void printOrd(vector<int> ord);
};
#endif /* _TOPOLOGICAL_ */
/*
* Topological.cpp
*
* Created on: 2014年6月3日
* Author: zhongchao
*/
#include "Topological.h"
Topological::Topological(DirWeightGraph* graph, int n)
{
mark = new bool[graph->v()];
for(int i = 0; i < graph->v(); i++)
{
mark[i] = false;
}
edgeTo = new int[graph->v()];
hash_set<int> nodes = graph->getNodes();
for(int i = 0; i < 13; i++)
{
if(mark[i] == false)
dfs(graph, i);
}
}
void Topological::dfs(DirWeightGraph* graph, int n)
{
mark[n] = true;
vector<DirWeightEdge* > ns = graph->getAdj(n);
pre.push_back(n); //前序
for(vector<DirWeightEdge*>::iterator it = ns.begin(); it != ns.end(); it++)
{
int t = (*it)->to();
if(mark[t] == true) continue;
edgeTo[t] = n;
dfs(graph, t);
}
last.push_back(n); //后序
reLast.push_back(n); //逆后续
}
vector<int> Topological::order()
{
vector<int> ord;
for(vector<int>::reverse_iterator it = reLast.rbegin(); it != reLast.rend(); it++)
{
ord.push_back(*it);
}
return ord;
}
void Topological::printOrd(vector<int> ord)
{
for(vector<int>::iterator it = ord.begin(); it != ord.end(); it++)
{
cout<<*it<<"->";
}
cout<<"#"<<endl;
}
Topological::~Topological()
{
delete[] mark;
delete[] edgeTo;
}
void dfsTopological()
{
string path("/home/zhongchao/worksapce/cpp/ComputeAlgorithms/data/tinyDAG.txt");
DirWeightGraph* graph = new DirWeightGraph(path);
int n = 0;
Topological* topologocal = new Topological(graph, n);
vector<int> ord = topologocal->order();
topologocal->printOrd(ord);
}
/*
* Run.cpp
*
* Created on: 2014年5月25日
* Author: zhongchao
*/
#include "Graph.h"
#include "Prim.h"
#include "Dijkstra.h"
#include "DFS.h"
#include "BFS.h"
#include "CC.h"
void dfsTopological();
int main(int argc, char** argv)
{
dfsTopological();
return 1;
}
3 拓扑排序后的顺序为
8->7->2->3->0->5->1->6->9->11->10->12->4->#