Search code examples
pythondictionarynetworkxdepth-first-searchbreadth-first-search

find path and convert from dictionary to list


I am 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.

Here's what I've done so far:

BFS = 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.

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


Solution

  • Use a list comprehension and imply add .keys() to the end of your dictionaries:

    DFS = nx.bfs_successors(mazePRIM,start)
    print([n for n in dict(BFS).keys()])
    
    DFS = nx.dfs_successors(mazePRIM, start)
    print([n for n in DFS.keys()])
    

    You can read more about dictionary keys here:

    How to return dictionary keys as a list in Python?