title: How to find the nearest node using BFS?
body: <p>Let <code>G(V,E)</code> be an undirected unweighted graph and <code>r</code> be a subset of <code>V</code>. Now node <code>root</code> is added to <code>G</code> and edges are added between <code>root</code> and all the nodes of <code>r</code>. Now for each node of <code>V-r</code> I want to find the nearest node of <code>r</code> using BFS. Please help. I have tried the following code.</p>
  <pre><code>import networkx as nx
  import matplotlib.pyplot as plt
  
  def bfs(g, node):
      dist = 0
      visited = [node]
      queue = [(node, dist)]
      tr = {}
      while queue:
          s, dist = queue.pop(0)
          tr[s] = []
          for nbr in list(g.adj[s]):
              if nbr not in visited:
                  visited.append(nbr)
                  tr[s].append(nbr, dist+1)
                  queue.append((nbr, dist+1))
      return tr
  
  G=nx.erdos_renyi_graph(50,0.1)
  
  r=[5,8,36,43,21]
  G.add_node('root')
  for i in r:
      G.add_edge(i,'root')
  
  t = bfs(G, 'root')
  print(t)
  </code></pre>