1
- function TopoSortRecursiveFunction ( graph , visited , stack , path , vertex ) {
2
- //marking current vertex as visited
3
- visited . add ( vertex )
4
-
5
- //marking current vertex as being part of current path
6
- path [ vertex ] = 1
7
- if ( graph [ vertex ] && graph [ vertex ] . length !== 0 ) {
1
+ function TopoSort ( graph ) {
2
+ const n = graph . length
3
+ const result = [ ]
4
+ const path = Array ( n ) . fill ( 0 )
5
+ const visited = Array ( n ) . fill ( 0 )
6
+ function preorder ( vertex ) {
7
+ visited [ vertex ] = 1
8
+ path [ vertex ] = 1
8
9
for ( const neighbor of graph [ vertex ] ) {
9
- //if neighbor is not visited then visit else continue
10
- if ( ! visited . has ( neighbor ) ) {
11
- TopoSortRecursiveFunction ( graph , visited , stack , path , neighbor )
12
- } else if ( path [ neighbor ] == 1 ) return
10
+ if ( visited [ neighbor ] === 0 ) {
11
+ preorder ( neighbor )
12
+ } else if ( path [ neighbor ] === 1 ) {
13
+ throw new Error ( 'Graph contsins a cycle' )
14
+ }
13
15
}
16
+ path [ vertex ] = 0
17
+ result . push ( vertex )
18
+ }
19
+ return function ( ) {
20
+ for ( let i = 0 ; i < n ; i ++ ) {
21
+ if ( visited [ i ] === 0 ) {
22
+ try {
23
+ preorder ( i )
24
+ } catch ( err ) {
25
+ console . log ( err )
26
+ return null
27
+ }
28
+ }
29
+ }
30
+ return result . reverse ( )
14
31
}
15
-
16
- //unmarking vertex
17
- path [ vertex ] = 0
18
-
19
- //visited all vertex coming after the current vertex
20
- //so added to stack
21
- stack . push ( vertex )
22
32
}
23
-
24
33
/**
25
34
*
26
35
* @author {RaviSadam}
@@ -36,24 +45,6 @@ function TopoSortRecursiveFunction(graph, visited, stack, path, vertex) {
36
45
*
37
46
*/
38
47
export function TopoSortRecursive ( graph ) {
39
- const n = graph . length
40
- const stack = [ ]
41
- //visited set for keep tracking of visited vertises
42
- const visited = new Set ( )
43
-
44
- //path array for keep tacking of vertices
45
- //visited in current path
46
-
47
- const path = Array ( n ) . fill ( 0 )
48
- for ( let i = 0 ; i < n ; i ++ ) {
49
- if ( ! visited . has ( i ) ) {
50
- TopoSortRecursiveFunction ( graph , visited , stack , path , i )
51
- }
52
- }
53
- for ( const value of path ) {
54
- if ( value === 1 ) return null
55
- }
56
- //reverse the stack for getting exact topological order
57
- stack . reverse ( )
58
- return stack
48
+ const topoSort = TopoSort ( graph )
49
+ return topoSort ( )
59
50
}
0 commit comments