Unique Paths

A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).

The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).

How many possible unique paths are there?

1,1

1,2,

2,1

2,2

Above is a 3 x 7 grid. How many possible unique paths are there?

Solution

class Solution:
    """
    @param n and m: positive integer(1 <= n , m <= 100)
    @return an integer
    """ 
    def uniquePaths(self, m, n):
        if m <= 0 or n <= 0 :
            return 0
        F = [[0 for y in range(n)] for x in range(m)]

        F[0][0] = 1

        for i in range(1, m):
            F[i][0] = 1
        for j in range(1, n):
            F[0][j] = 1

        for i in range(1, m):
            for j in range(1, n):
                F[i][j] = F[i][j-1] + F[i-1][j]

        return F[-1][-1]

Last updated

Was this helpful?