Skip to content

Function to return the adjacent nodes of a given node at a distance greater than 1 #288

Closed
@Tortar

Description

@Tortar

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions