Unique Paths in Python


Suppose there is a robot is located at the top-left corner of a n x m grid (n rows and m columns). The robot can only move either down side or right side at any point in time. The robot wants to reach the bottom-right corner of the grid (marked 'END in the diagram below). So we have to find how many possible unique paths are there? For example if m = 3 and n = 2, then the grid will be like below −

Robo



END

The output will be 3, So there are total 3 different ways to reach from start position to the end position. These paths are −

  1. Right → Right → Down
  2. Right → Down → Right
  3. Down → Right → Right

Let us see the steps −

  • We will use the dynamic programming approach to solve this
  • let row := n and col := m, create a table DP of order n x m and fill this with -1
  • DP[row – 2, col - 1] := 1
  • for i in range 0 to col
    • DP[n – 1, i] := 1
  • for i in range 0 to row
    • DP[i, col – 1] := 1
  • for i in range row -2 down to -1
    • for j in range col -2 down to -1
      • DP[i, j] := DP[i + 1, j] + DP[i, j + 1]
  • return DP[0, 0]

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution(object):
   def uniquePaths(self, m, n):
      row = n
      column = m
      dp = [[-1 for i in range(m)] for j in range(n)]
      dp[row-2][column-1] = 1
      for i in range(column):
         dp[n-1][i] = 1
      for i in range(row):
         dp[i][column-1]=1
      for i in range(row-2,-1,-1):
         for j in range(column-2,-1,-1):
            dp[i][j] = dp[i+1][j] + dp[i][j+1]
      return dp[0][0]
ob1 = Solution()
print(ob1.uniquePaths(10,3))

Input

10
3

Output

55

Updated on: 04-May-2020

508 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements