简体   繁体   中英

find all paths in graph without start or end node

I'm playing a game in which to proceed to the next level, we must defeat each level before it. Each level corresponds to a certain letter.

I've represented this as a graph traversal problem, but I'm trying to find all paths in a graph without a start or end node.

My graph is represented as a dictionary, with the key being strings and the values being a list of strings.

{
'A2': ['A1', 'B'], 
'A1': [], 
'B': [], 
'C': ['A2'],
 }

To go to level A2, we must complete A1 and B.

For example, an example path would be A1, B, A2, C. Another path could be B, A1, A2, C.

Implementations of depth first search or breadth first search require a start node. I'm thinking a good start node would be any key whose values are empty: in this case, A1 and B, but I'm uncertain how to implement dfs or bfs with two start nodes.

I've been working with tweaking this implementation of finding paths, but this only works with a start level and an end level.

def find_path(graph, start, end, path=[]):
        path = path + [start]
        if start == end:
            return path
        if start not in graph:
            return None
        for node in graph[start]:
            if node not in path:
                newpath = find_path(graph, node, end, path)
                if newpath: return newpath
        return None

print(find_path(course_dict, 'A1', 'PC'))

but I'm getting None for my answer.

Okay, two problems. First you are trying to built a recursive algorithm but you still use a for loop. That is confusing, you can do this without the for loop. It is not wrong to use a loop in a recursive algorithm but if you change your data structure you do not need to.

Second thing is that your dictionary is wrong. I assume that every key of the dictionary is the staring node and every value is a possible end node. This is how your algorithm currently works. In that case the end node for your start A1 is not given. Therefore you get the None output.

The biggest problem is that you use the wrong algorithm. This algorithm finds a way from your start to your end node. But you want to ensure that every node between your start and end node is at least once visited. So you can either change the algorithm (which would be easy) or the data structure (which will lead to a lot of variations).

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