简体   繁体   中英

How do I make my recursive algorithm to stop once the target is reached?

I am trying to solve a problem for the following question.

Find path for a robot in a maze from top left corner to bottom right corner. The robot can move only to the right or bottom. There are certain restricted areas where the robot cannot go into.

My idea is to use depth first search going right first and then going bottom. My algorithm is working. But I have gotten quite rusty with recursion. I am not able to return the output properly. This is my code

def robot_path(r, c, off_limits):
    """
    r -> number of rows in grid
    c -> number of columns in grid
    off_limits -> nested list containing positions of restricted areas
    """
    grid = list()
    for i in range(0, r):
        grid.append([1] * c)
    for off_limit in off_limits:
        grid[off_limit[0]][off_limit[1]] = 'X'
    path = list()
    return __move(grid, (0,0), path, (r-1, c-1))

def __move(grid, position, path, target):
    if position == target:
        return path
    x = position[0]
    y = position[1]
    if x < len(grid) and y < len(grid[0]):
        if grid[x][y] != 'X':
            path.append(1)
            __move(grid, (x, y+1), path, target)
            path.pop()
            path.append(0)
            __move(grid, (x+1, y), path, target)
            path.pop()

How can I return the path? In the path list, 0 means moving bottom and 1 means moving right. However, my algorithm does not stop once it reaches the bottom right. It runs even after that and I'm getting a None output. How do i change this to return my path once the bottom right is reached.

Test output

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

should return

[1, 0, 1, 1, 0, 0]

Without simply giving the answer, I would suggest thinking about the following

  • The second function doesn't have a return in all paths, only in the first if
  • Recursive functions are usually not combined with mutable objects. Your path object is mutated using pop() . Usually in recursive functions it is clearer if objects are only passed and returned, not mutated inline

eg:

def sum(l):
    if len(l) == 0:
        return 0
    return l[0] + sum(l[1:])

The tail is passed down to the next function, the result is passed back up the chain. The list itself is not mutated within the sum() function, just broken into pieces for the purpose of passing down.

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