-
Notifications
You must be signed in to change notification settings - Fork 103
fix is_cyclic #168
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
fix is_cyclic #168
Changes from all commits
c3b2561
bc02277
2024eb7
05cb957
f056203
2f02612
2a21c58
c8ad5d7
f667c1f
dda80ad
7af46af
64486d8
f2edf24
bc73585
a1b9f9d
2a0de95
487dd1e
260632c
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change | ||
---|---|---|---|---|
|
@@ -7,10 +7,29 @@ | |||
Return `true` if graph `g` contains a cycle. | ||||
|
||||
### Implementation Notes | ||||
Uses DFS. | ||||
The algorithm uses a DFS. Self-loops are counted as cycles. | ||||
""" | ||||
function is_cyclic end | ||||
@traitfn is_cyclic(g::::(!IsDirected)) = ne(g) > 0 | ||||
@enum Vertex_state unvisited visited | ||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
Since this enum is binary, I believe it's clearer to replace it by a vector of booleans. It's actually also slightly more memory-friendly since those can be nicely packed into a |
||||
@traitfn function is_cyclic(g::AG::(!IsDirected)) where {T, AG<:AbstractGraph{T}} | ||||
visited = falses(nv(g)) | ||||
for v in vertices(g) | ||||
visited[v] && continue | ||||
visited[v] = true | ||||
S = [(v,v)] | ||||
while !isempty(S) | ||||
parent, w = pop!(S) | ||||
for u in neighbors(g, w) | ||||
u == w && return true # self-loop | ||||
u == parent && continue | ||||
visited[u] && return true | ||||
visited[u] = true | ||||
push!(S, (w, u)) | ||||
end | ||||
end | ||||
end | ||||
return false | ||||
end | ||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This looks correct to me, but there is a small edge that we also have to consider: If an undirected graph has a self-loop (i.e. a vertex that is connected to itself), then this should also count as a cycle in my opinion. (or if not, at least we have to document this). |
||||
# see https://github.com/mauro3/SimpleTraits.jl/issues/47#issuecomment-327880153 for syntax | ||||
@traitfn function is_cyclic(g::AG::IsDirected) where {T, AG<:AbstractGraph{T}} | ||||
vcolor = zeros(UInt8, nv(g)) | ||||
|
Uh oh!
There was an error while loading. Please reload this page.