You are on page 1of 2

[head]

Topological Order (InDegree)


[/head]
[para]
Here is a topological sort using indegree algorithm. The Code is pretty self exp
lainatory.
[/para]
[code]
/*
topological sort with indegree algo
FileName: TopoInDeg.cpp
author : dumb_terminal
*/
#include <iostream>
#include <queue>
#include <vector>
using namespace std ;
#define MAX 100
/* No of Vertex and Edges */
int V, E ;
/* the Graph */
vector < int > G[MAX] ;
/* the indegree array */
int IN[MAX] ;
/* the topological order */
vector < int > topo ;
/* reset and prepare a Graph for a new sort */
void reset(){
for (int i = 0 ; i <= V ; i++)
G[i].clear() ;
topo.clear() ;
memset(IN, 0, sizeof(IN)) ;
}
/* the sort */
void topo_indegree(){
int i ;
queue < int > Q ;
for (i = 0 ; i < V ; i++)
if (!IN[i]) Q.push(i) ;
if (Q.empty())
cout << "There is a cycle thus no topological sort\n" ;
while (!Q.empty()){
int u = Q.front() ;
IN[u]-- ;
Q.pop() ;
int sz = G[u].size() ;
for (int i = 0 ; i < sz ; i++){
int v = G[u][i] ;
IN[v]-- ;
if (!IN[v]) Q.push(v) ;
}
topo.push_back(u) ;
}
}
int main(){
int i, u, v ;
/* Enter the No of Vertex and Edges V = E = 0 ends*/
while (cin >> V >> E && V && E){
reset() ;
for (i = 0 ; i < E ; i++){
cin >> u >> v ; /* v depends on u */
G[u].push_back(v) ;
IN[v]++ ;
}
topo_indegree() ;
int sz = topo.size() ;
for (i = 0 ; i < sz ; i++)
cout << topo[i] << " " ;
cout << endl ;
}
}
[/code]
[sig]
Sayeed Mahmud
Batch 15 Roll 05
Dept. Of Computer Science & Engineering
University of Dhaka
[Handle - dumb_terminal]
[/sig]

You might also like