简体   繁体   中英

Find a path between two values in a dictionary in Python

I am trying to find the path between two elements in a dictionary . Let me explain the situation. Using NetworkX I created a graph and using bfs_successors and dfs_successors I created two trees , saved in two dictionaries , as you can see

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)]}

Now I need to get the "path" between the root/start, (0,0), and an end node, for example (1,3). How can I get it?

So I need a function to search the end node and to return the path between start and end.

And is it possible to write it this way?

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

I think the idea of networkx (although I've never used it) is probably that you'd use a function like shortest_path to find the path between two specific nodes, and you'd only use the dfs/bfs functions if you want an exhaustive list of all the reachable nodes.

That said, if you wanted to roll your own DFS using the dictionary you got from those functions, here's an example:

>>> from typing import Dict, List, Tuple
>>>
>>>
>>> def dfs(
...     graph: Dict[Tuple[int, int], List[Tuple[int, int]]],
...     path: List[Tuple[int, int]],
...     target: Tuple[int, int]
... ) -> List[Tuple[int, int]]:
...     """Given a graph and a starting path, return the
...     complete path through the graph to the target."""
...     if path[-1] == target:
...         return path
...     if path[-1] not in graph:
...         return []
...     for node in graph[path[-1]]:
...         if node in path:
...             continue
...         maybe_path = dfs(graph, path + [node], target)
...         if len(maybe_path):
...             return maybe_path
...     return []
...
>>>
>>> print(dfs(
...     {(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)],
...     (1, 3)
... ))
[(0, 0), (1, 0), (1, 1), (1, 2), (1, 3)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM