convert output from dictionary to list with bfs and dfs networkx

狂风中的少年 提交于 2020-06-29 03:50:15

问题


I am currently using networkx library for Python with BFS and DFS. I need to get a tree and then explore it to get a path from a start node to an end node.

For the BFS part I am using bfs_successorsand it returns an iterator of successors in breadth-first-search from source.

For the DFS part I am using: dfs_successors and it returns a dictionary of successors in depth-first-search from source.

I need to get a list of nodes from source to end from both the algorithms. Each node is (x, y) and is a cell in a grid.

Do you have any advice about how to do it? Can you help me please?

MWE:

DFS = nx.bfs_successors(mazePRIM,start)
print(dict(BFS))

DFS = nx.dfs_successors(mazePRIM, start)
print(DFS)

and I get this:

{(0, 0): [(0, 1), (1, 0)], (1, 0): [(1, 1)], (1, 1): [(1, 2)], (1, 2): [(0, 2), (1, 3)], (0, 2): [(0, 3)]}

{(0, 0): [(0, 1), (1, 0)], (1, 0): [(1, 1)], (1, 1): [(1, 2)], (1, 2): [(0, 2), (1, 3)], (0, 2): [(0, 3)]}

But I need an output like this:

[(0, 0), (1, 0), (1, 1), (1, 2), (1, 3)]

which is the list of nodes from start to end.


回答1:


IIUC you're not really interested in finding all successors encourtered with nx.bfs_successors, since you only need the path between a source and a target nodes.

For that you can either find the shortest path (in the case there are multiple):

nx.shortest_path(G, source, target)

Or find all simple paths between them:

nx.all_simple_paths(G, source, target)

Which returns a generator with all simple paths between both nodes.



来源:https://stackoverflow.com/questions/62412222/convert-output-from-dictionary-to-list-with-bfs-and-dfs-networkx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!