Hello all,
I would like to create a graph with no weights and efficiently test if vertices are connected (not necessarily neighbors).
I learned I can do this using shortest_path algorithms and connected_components but I wanted to see if there was a more efficient way, especially as the graph complexity grows.
MWE:
using BenchmarkTools
using Graphs
using Random
function is_connected_using_shortest_path(g, source, sink)
# If there's a more efficient algorithm than a_star, let me know please
paths = a_star(g, source, sink);
return length(paths) > 0;
end
function is_connected_using_connected_components(g, source, sink)
for cluster in connected_components(g)
if source in cluster && sink in cluster
return true;
end
end
return false;
end
# Creating graph: (1)--(2)--(3) (4)--(5)
g = path_graph(5);
rem_edge!(g, 3, 4);
Random.seed!(1234);
display(@benchmark is_connected_using_shortest_path(g, data[1], data[2]) setup=(data=rand(collect(1:5), 2)))
Random.seed!(1234);
display(@benchmark is_connected_using_connected_components(g, data[1], data[2]) setup=(data=rand(collect(1:5), 2)))
Output
BenchmarkTools.Trial: 10000 samples with 186 evaluations.
Range (min β¦ max): 555.914 ns β¦ 29.407 ΞΌs β GC (min β¦ max): 0.00% β¦ 93.17%
Time (median): 694.086 ns β GC (median): 0.00%
Time (mean Β± Ο): 825.910 ns Β± 1.122 ΞΌs β GC (mean Β± Ο): 8.80% Β± 6.43%
β βββββ
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
556 ns Histogram: frequency by time 2.24 ΞΌs <
Memory estimate: 1.09 KiB, allocs estimate: 12.
BenchmarkTools.Trial: 10000 samples with 189 evaluations.
Range (min β¦ max): 523.810 ns β¦ 42.610 ΞΌs β GC (min β¦ max): 0.00% β¦ 95.61%
Time (median): 593.651 ns β GC (median): 0.00%
Time (mean Β± Ο): 811.357 ns Β± 1.622 ΞΌs β GC (mean Β± Ο): 14.10% Β± 7.06%
ββββββββββββββββββ β β β
βββββββββββββββββββββββββββββββββββββββββββββ
β
β
ββ
β
ββ
β
ββ
β
βββ
β β
524 ns Histogram: log(frequency) by time 2.07 ΞΌs <
Memory estimate: 1.31 KiB, allocs estimate: 15.
EDIT1: Removed NetworkX link. I thought they have a function to do this.