简体   繁体   中英

Can anyone tell me why my DFS algorithm isn't returning the shortest path? (Python)

Basically exactly what the title says. I have a DFS algorithm that seems to work ok at first glance but, while it does return a path, it doesn't return the shortest path and I am not sure what is wrong unfortunately. Any help would be greatly appreciated! Thank you!

def shortestPathDFSNoRecursion( start, end ):
    path = []

    stack = []
    stack.append( start )

    best_path = None
    best_length = math.inf # a big number

    while stack:
        current_position = stack.pop()

        if current_position == end:
            if len(path) < best_length:
                best_length = len(path)
                best_path = path

        if current_position.y < 0 or \
           current_position.x < 0 or \
           current_position.y >= len(maze) or \
           current_position.x >= len( maze[ current_position.y ] ):
            continue

        if not maze[ current_position.y ][ current_position.x ] == " " or current_position in path:
            continue

        path.append( current_position )

        for direction in DIRECTIONS.values():  # up, down, right, left
            stack.append( Vec2( current_position.x + direction.x, current_position.y + direction.y ) )

    return best_path

You append to path every time you visit a node, but it doesn't get reset when you backtrack because you reached a dead end.

There's more than one approach to dealing with this, but the simplest is simply to have your stack store a tuple or structure that contains a position to visit and the path used to get there.

And as Tim Roberts says, what you've written isn't DFS, it's BFS. One nice thing about that is that it makes your "best_length" check completely superfluous. BFS checks paths in order of their length, so the very first path you find that reaches the target will be a shortest path.

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