-3

I have to write a function that will return a set that contains neighbours of a source vertex in given distance. For example for exemplary graph:

        {0: [1, 3],
         1: [2],
         2: [],
         3: [4],
         4: [1, 5],
         5: [],
         6: [1]}

By passing this graph to a function + the source vertex which is 0 and passing distance = 2 the result should be: {1,2,3,4}.

How can I achieve that?

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
The Robcio
  • 33
  • 4

1 Answers1

0

I am not well versed in graph theory, but the following seems to get correct results. It gets the following for a distance of 2:

{1, 2, 3, 4}

import networkx as nx

def main():
    distance = 2
    source_node = 0

    dict1 = {0: [1, 3],
             1: [2],
             2: [],
             3: [4],
             4: [1, 5],
             5: [],
             6: [1]}

    g = nx.DiGraph()

    # fill graph
    for node, list1 in dict1.items():
        for n in list1:
            g.add_edge(node, n)

    neighbors = []
    M = [source_node]

    for _ in range(distance):
        M = find_neigbors(g,M)
        neighbors.extend(M)

    print(neighbors)

def find_neigbors(g, vertices):
    p = []
    for node in vertices:
        p.extend(g.adj[node])
    return p

main()

Update: Wikipedia has a Python function here that implements a BFS algorithm.

Update: See also BFS algorithm in Python

Chris Charley
  • 6,403
  • 2
  • 24
  • 26
  • Thanks for this :D However there's one more question that I'd like to ask. What does the g.adj[node] mean? I'm aware what extend function is responsible for, but I'm concerned when it comes to .adj[node]. Please be so kind and leave an additional comment on that :) – The Robcio Nov 04 '18 at 08:46
  • @The Robcio g.adj[node] returns the nodes immediately following the given node. I'm afraid I was too hasty in answering your question to note that you wanted s BFS algorithm. And I failed to provide that. Additionally, `p.extend(g.adj[node]}` could have more simply written `p += g.adj[node]` – Chris Charley Nov 04 '18 at 16:48
  • Ye, as I mentioned I've already met extend function a few times so I'm familiar with it I was just concerned about .adj one but now it's clear ;) Thanks for your answer – The Robcio Nov 04 '18 at 22:21