Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
201 views
in Technique[技术] by (71.8m points)

How do I find the distance from a source node to every other node using Breadth-First Search algorithm in Python

I have a graph that has nodes. For instance, the numbers represent people that know each other. I am using a dictionary, the key is every node and the values is a list of all the people(numbers) the key knows every value. I want to find the distance from the source node to every other node. In the following code, some of the results are incorrect. What am I doing wrong?

import itertools as itt
import operator as op
from typing import List, Dict, AnyStr, Tuple

def loadGraph(edgeFilename):
    array = []
    lst = []

with open(edgeFilename, "r") as f:
    for row in f:
        array.append(row.strip())
array[0] = array[0][1:]
for j in array:
    tup = (j[0], j[-1])
    lst.append(tup)
    
return lst


def to_dict(graph : List[Tuple[AnyStr,AnyStr]]) -> Dict[AnyStr,List[AnyStr]]:
    myDict = {}
    key = op.itemgetter(0)
    val = op.itemgetter(1)
    graph = [list(sorted(e)) for e in graph]
    keys = set(itt.chain.from_iterable(graph))

    for k in keys:
        for v in graph:
            if k in v:
                for j in v:
                    if k != j:
                        if k not in myDict:
                            myDict.update({k : [j]})
                        else:
                            myDict[k].extend([j])
    return myDict

graph = to_dict(loadGraph('d.csv'))

def bfs(graph, s):
queue = []
visited = []
queue.insert(0, s)
visited.insert(0, s)

array = []
dist = 1
level = 1

while queue != []:
    s = queue.pop()
    for i in graph[s]:
        if i not in visited:
            
            array.append({i : dist})
            queue.insert(0, i)
            visited.insert(0, i)
            
            dist=level
    level+=1
    
return array

Driver Code

print(bfs(graph, '2'))

Input would be from a .csv file and would be a list of lists or a list of tuples of every number that knows each other. This would be an undirected graph. If 2 knows 5, then 5 also knows 2.

Input = [[1,2],[2, 3],[1,5,],[3,4],[4,6],[2,5],[2,7],[3,7],[1,8]]

Then through a function would be transformed to a dictionary of everyone that knows each other.

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

This dictionary is the graph. The output I want will tell how far away every node is from the source node.

Example Source node = 2

Output = [{1:1},{3:1},{4:2},{5:1},{6:3},{7:1},{8:2}]

question from:https://stackoverflow.com/questions/65840618/how-do-i-find-the-distance-from-a-source-node-to-every-other-node-using-breadth

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...