From 69546054da457bd7ba7abae97f46dc1d2980c4f5 Mon Sep 17 00:00:00 2001 From: Thomas Christensen Date: Thu, 31 Oct 2024 15:55:51 +0100 Subject: [PATCH] speed up `has_path` by avoiding `popfirst!` and `push!` --- src/traversals/bfs.jl | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/src/traversals/bfs.jl b/src/traversals/bfs.jl index b98d4497e..eef17b6b9 100644 --- a/src/traversals/bfs.jl +++ b/src/traversals/bfs.jl @@ -182,15 +182,18 @@ function has_path( end (seen[u] || seen[v]) && return false u == v && return true # cannot be separated - next = Vector{T}() - push!(next, u) + next = Vector{T}(undef, nv(g)) + front = back = 1 + next[front] = u seen[u] = true - while !isempty(next) - src = popfirst!(next) # get new element from queue + while front <= back + src = next[front] + front += 1 # dequeue; pop from queue for vertex in outneighbors(g, src) vertex == v && return true if !seen[vertex] - push!(next, vertex) # push onto queue + back += 1 + next[back] = vertex # enqueue; push onto queue seen[vertex] = true end end