@@ -32,30 +32,30 @@ function is_cyclic end
32
32
end
33
33
# see https://github.com/mauro3/SimpleTraits.jl/issues/47#issuecomment-327880153 for syntax
34
34
@traitfn function is_cyclic (g:: AG :: IsDirected ) where {T,AG<: AbstractGraph{T} }
35
- # 0 if not visited, 1 if visited, 2 if in the current dfs path, 3 if fully explored
35
+ # 0 if not visited, 1 if in the current dfs path, 2 if fully explored
36
36
vcolor = zeros (UInt8, nv (g))
37
37
vertex_stack = Vector {T} ()
38
38
for v in vertices (g)
39
39
vcolor[v] != 0 && continue
40
40
push! (vertex_stack, v)
41
- vcolor[v] = 1
42
41
while ! isempty (vertex_stack)
43
42
u = vertex_stack[end ]
44
- if vcolor[u] == 1
45
- vcolor[u] = 2
43
+ if vcolor[u] == 0
44
+ vcolor[u] = 1
46
45
for n in outneighbors (g, u)
47
46
# we hit a loop when reaching back a vertex of the main path
48
- if vcolor[n] == 2
47
+ if vcolor[n] == 1
49
48
return true
50
49
elseif vcolor[n] == 0
51
50
# we store neighbors, but these are not yet on the path
52
- vcolor[n] = 1
53
51
push! (vertex_stack, n)
54
52
end
55
53
end
56
54
else
57
- vcolor[u] = 3
58
55
pop! (vertex_stack)
56
+ if vcolor[u] == 1
57
+ vcolor[u] = 2
58
+ end
59
59
end
60
60
end
61
61
end
@@ -87,32 +87,33 @@ graph `g` as a vector of vertices in topological order.
87
87
function topological_sort_by_dfs end
88
88
# see https://github.com/mauro3/SimpleTraits.jl/issues/47#issuecomment-327880153 for syntax
89
89
@traitfn function topological_sort_by_dfs (g:: AG :: IsDirected ) where {T,AG<: AbstractGraph{T} }
90
- # 0 if not visited, 1 if visited, 2 if in the current dfs path, 3 if fully explored
90
+ # 0 if not visited, 1 if in the current dfs path, 2 if fully explored
91
91
vcolor = zeros (UInt8, nv (g))
92
92
verts = Vector {T} ()
93
93
vertex_stack = Vector {T} ()
94
94
for v in vertices (g)
95
95
vcolor[v] != 0 && continue
96
96
push! (vertex_stack, v)
97
- vcolor[v] = 1
98
97
while ! isempty (vertex_stack)
99
98
u = vertex_stack[end ]
100
- if vcolor[u] == 1
101
- vcolor[u] = 2
99
+ if vcolor[u] == 0
100
+ vcolor[u] = 1
102
101
for n in outneighbors (g, u)
103
102
# we hit a loop when reaching back a vertex of the main path
104
- if vcolor[n] == 2
103
+ if vcolor[n] == 1
105
104
error (" The input graph contains at least one loop." ) # TODO 0.7 should we use a different error?
106
105
elseif vcolor[n] == 0
107
106
# we store neighbors, but these are not yet on the path
108
- vcolor[n] = 1
109
107
push! (vertex_stack, n)
110
108
end
111
109
end
112
- else
113
- vcolor[u] = 3
110
+ else
114
111
pop! (vertex_stack)
115
- pushfirst! (verts, u)
112
+ # if vcolor[u] == 2, the vertex was already explored and added to verts
113
+ if vcolor[u] == 1
114
+ vcolor[u] = 2
115
+ pushfirst! (verts, u)
116
+ end
116
117
end
117
118
end
118
119
end
0 commit comments