Grid Traveler

Brute force

def grid_traveler_brute_force(m: int, n: int) -> int:
    """
    Time complexity: O(2^(N+M))
        For each recursive call, we will make two calls (one for each type 
        of movement we are allowed to do). And, if we explore the height 
        of the recursive tree it will depend both in M and N. 
        Since we only can move towards one direction at every step, 
        the max height will depend on M+N.
    
    Space complexity: O(N+M)
        Since the max height is N+M, the max size of the stack will be 
        limited by it.
    """

    if m == 1 and n == 1:
        return 1
    elif m == 0 or n == 0:
        return 0
    
    return grid_traveler(m - 1, n) + grid_traveler(m, n - 1)

Memoization

Tubulation

From down-right to top-left

From top-left to down-right

Last updated

Was this helpful?