Skip to content

Commit d4f0502

Browse files
amontoisongdalle
andauthored
Use a more efficient queue in TreeSetResult (#94)
* Use a more efficient queue in TreeSetResult * Format --------- Co-authored-by: Guillaume Dalle <22795598+gdalle@users.noreply.github.com>
1 parent e780a5b commit d4f0502

1 file changed

Lines changed: 19 additions & 9 deletions

File tree

src/result.jl

Lines changed: 19 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -278,41 +278,51 @@ function TreeSetColoringResult(
278278
# reverse breadth first (BFS) traversal order for each tree in the forest
279279
reverse_bfs_orders = [Tuple{Int,Int}[] for i in 1:ntrees]
280280

281+
# nvmax is the number of vertices of the biggest tree in the forest
282+
nvmax = mapreduce(length, max, vertices_by_tree)
283+
284+
# Create a queue with a fixed size nvmax
285+
queue = Vector{Int}(undef, nvmax)
286+
281287
for k in 1:ntrees
282288
tree = trees[k]
283289

284-
# queue to store the leaves
285-
queue = Int[]
290+
# Initialize the queue to store the leaves
291+
queue_start = 1
292+
queue_end = 0
286293

287294
# compute the degree of each vertex in the tree
288-
for (vertex, neighbors) in trees[k]
295+
for (vertex, neighbors) in tree
289296
degree = length(neighbors)
290297
degrees[vertex] = degree
291298

292299
# the vertex is a leaf
293300
if degree == 1
294-
push!(queue, vertex)
301+
queue_end += 1
302+
queue[queue_end] = vertex
295303
end
296304
end
297305

298306
# continue until all leaves are treated
299-
while !isempty(queue)
300-
leaf = pop!(queue)
307+
while queue_start <= queue_end
308+
leaf = queue[queue_start]
309+
queue_start += 1
301310

302-
# Convenient way to specify that the vertex is removed
311+
# Mark the vertex as removed
303312
degrees[leaf] = 0
304313

305314
for neighbor in tree[leaf]
306315
if degrees[neighbor] != 0
307316
# (leaf, neighbor) represents the next edge to visit during decompression
308317
push!(reverse_bfs_orders[k], (leaf, neighbor))
309318

310-
# reduce the degree of all neighbors
319+
# reduce the degree of the neighbor
311320
degrees[neighbor] -= 1
312321

313322
# check if the neighbor is now a leaf
314323
if degrees[neighbor] == 1
315-
push!(queue, neighbor)
324+
queue_end += 1
325+
queue[queue_end] = neighbor
316326
end
317327
end
318328
end

0 commit comments

Comments
 (0)