Closed
Description
I'd like to propose an extension to the neighbors
function (neighbors
, inneighbors
, outneighbors
, all_neighbors
) such that it is possible to find the adjacent nodes of a given node of a graph at a distance greater than 1.
For a starting implementation, this is a slightly modified version we use in Agents.jl to find the neighbors nodes in a graph for an arbitrary distance:
using Graphs
function nearby_positions(graph, node::Integer, radius::Integer)
nearby = copy(nearby_positions(graph, node))
radius == 1 && return nearby
seen = Set{Int}(nearby)
push!(seen, node)
k, n = 0, nv(graph)
for _ in 2:radius
thislevel = @view nearby[k+1:end]
isempty(thislevel) && return nearby
k = length(nearby)
k == n && return nearby
for v in thislevel
for w in nearby_positions(graph, v)
if w ∉ seen
push!(seen, w)
push!(nearby, w)
end
end
end
end
return nearby
end
function nearby_positions(graph, node::Int, neighbor_type::Symbol = :default,)
if neighbor_type == :default
neighbors(graph, node)
elseif neighbor_type == :in
inneighbors(graph, node)
elseif neighbor_type == :out
outneighbors(graph, node)
else
all_neighbors(graph, node)
end
end
Here the extension returns a new vector, I think it would be probably better to return an iterator instead. Networkx can do it with the single_shortest_path_length
function
edit: sorry for the bug label, didn't notice that the issue template I used would have automatically added it