In the upper left corner of the N * M grid there is a robot. The robot can move up, down, left and right, but cannot visit the same cell more than once in each round. How to find the total number of ways that a robot can get into the lower right corner?
(the robot does not need to visit each cell in order for the path to be valid)
I think there is a recursive solution, but I just can't figure it out.
Here is what I have so far:
def initialize(row, cols):
grid = [ [ 0 for c in range(cols) ] for r in range(rows) ]
pos_r, pos_c = 0, 0
grid[pos_r][pos_c] = 1
dst_x, dst_y = len(grid)-1, len(grid[0])-1
print move_robot(grid, dst_x, dst_y, pos_r, pos_c)
def move_robot(grid, dst_x, dst_y, pos_r, pos_c, prev_r=None, prev_c=None):
num_ways = 0
if reached_dst(dst_x, dst_y, pos_r, pos_c):
undo_move(grid, pos_r, pos_c)
undo_move(grid, prev_r, prev_c)
return 1
else:
moves = get_moves(grid, pos_r, pos_c)
if len(moves) == 0:
undo_move(grid, prev_r, prev_c)
return 0
for move in moves:
prev_r = pos_r
prev_c = pos_c
pos_r = move[0]
pos_c = move[1]
update_grid(grid, pos_r, pos_c)
num_ways += move_robot(grid, dst_x, dst_y, pos_r, pos_c, prev_r, prev_c)
return num_ways
if __name__ == '__main__':
initialize(4, 4)
. Get_moves , , - . Update_grid '1', . Undo_move , "0".
( 2 * 2), . , ?