Ask a Question

 

Start Coding Today

   

GeeksQuiz

GeeksforGeeksIDE

Data Structures

Algorithms

Interview Experiences

C Programming

C++ Programming

Java Programming

GATE CS

Books

Number of unique paths

A robot is located at the top-left corner of an A x B 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?

Note: A and B will be such that the resulting answer fits in a 32 bit signed integer.

Example :

Input : A = 2, B = 2
Output : 2

2 possible routes : (0, 0) -> (0, 1) -> (1, 1) 
              OR  : (0, 0) -> (1, 0) -> (1, 1)
asked Oct 1, 2015 by Gaurav

7 Answers

+19 votes
 
Best answer

There is a mathematical approach to solving this problem.

Note that you have to take m + n - 2 steps in total. You have to take (m - 1) steps going down and (n-1) steps going right.

Let 0 denote a down step and 1 denote a right step.

So we need to find out the number of strings of length m + n - 2 which have exactly m - 1 zeroes and n - 1 ones.

Essentially we need to choose the positions of ‘1s’, and then ‘0s’ fall into the remaining positions.

So, the answer becomes Choose(m+n-2, n - 1).

 

int uniquePaths(int m, int n) {
    // m+n-2 C n-1 = (m+n-2)! / (n-1)! (m-1)! 
    long long ans = 1;
    for (int i = n; i < (m + n - 1); i++) {
        ans *= i;
        ans /= (i - n + 1);
    }
    return (int)ans;
}

 

answered Oct 1, 2015 by Swanky
selected Nov 9, 2015 by Gaurav
I can't understand why we need to choose the positions of ‘1s’, and then ‘0s’ fall into the remaining positions.

We have total of m+n-2 paths to travel, out of which we have to choose m-1 for traveling towards right, and the rest for traveling downwards.

So, we can choose m-1 paths out of total m+n-2 by  C (m+n-2, m-1), and the remaining n-1 paths out the remaining (m+n-2) - (m-1) by  C (m+n-2-m+1, n-1)  =  C (n-1 ,n-1)

Therefore multiplying both we get  C (m+n-2, m-1) * 1 = C (m+n-2, m-1)

I get that thank you very much .

_/\_ Best way to think.

 

thanx for ur explanation

+11 votes

You can solve this problem using dynamic programming too ,   As we can see that at every position  you can reach either from above or from left, so   ways at i, j will be equal to sum of ways  from  i, j-1   and  and ways from  i-1, j  ,    so simple code can be written as - 

int cntways(int m, int n)
{
    int ways[m][n];
    for (int i = 0; i < m; ++i)
    {
        for (int j = 0; j < n; ++j)
        {
            if(i == 0 && j == 0)
                ways[i][j] = 1;
            else if(i == 0)
                ways[i][j] = ways[i][j-1];
            else if(j == 0)
                ways[i][j] = ways[i-1][j];
            else
                ways[i][j] = ways[i-1][j] + ways[i][j-1];
        }
    }
    
    return ways[m-1][n-1];
}

 

answered Nov 12, 2015 by utkarsh111
+3 votes

There is another easy way to understand "Mathematical Solution" for this problem as follows.

1. For M X N matrix , we essentially have to take (M-1) down steps and (N-1) right steps in order to reach Finishing point. 

2. Lets us denote down steps by letter 'D' and right step  by "R".

3. Now agree that all combinations or permutations of (m-1) D's and (n-1) R's will reach to Finish point. It does not matter when you take right step and when you take down step.

4. So answer is to find number of all permutations of (D,D,D,....(m-1) times , R,R,R,....(n-1) times) which is equal to (m-1 + n-1)!/(m-1)!(n-1)!

 

answered Apr 17, 2016 by Sahil Rally

thanks for this wonderful explanation :)

0 votes

I have taken a recursive approach but it gets timed out.    

public int uniquePaths(int m, int n) {
        if( m == 1 && n == 1  )
            return 1;
        if( m == 1 ) return uniquePaths( 1, n -1 );
        if( n == 1 ) return uniquePaths( m-1, 1 );
        return uniquePaths( m - 1, n ) + uniquePaths( m, n-1 );
    }

answered Sep 14, 2016 by Mohit
edited Sep 16, 2016
0 votes

def unique_path(m,n):
    path = []
    for i in xrange(0,m+1):
        path.append([])
        for j in xrange(0,n+1):
            path[i].append(1)

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

   return path[m][n]

answered Sep 17, 2016 by anonymous
0 votes

Dynamic programming. Bottom-up approach.

    def uniquePaths(self, m, n):
        """
        :type m: int
        :type n: int
        :rtype: int
        """
        DP = [[0 for j in xrange(n)] for i in xrange(m)]
        
        DP[m-1][n-1] = 0
        
        for i in xrange(m):
            DP[i][n-1] = 1
            
        for j in xrange(n):
            DP[m-1][j] = 1
            
        for i in xrange(m-2, -1, -1):
            for j in xrange(n-2, -1, -1):
                DP[i][j] = DP[i][j+1] + DP[i+1][j]
                
        return DP[0][0]

 

answered Nov 4, 2016 by Prem
0 votes

 


class RoboProblem
{
public int uniquePaths(int m, int n) {
    if(m==0 || n==0) return 0;
    if(m==1 || n==1) return 1;
 
    int[][] dp = new int[m][n];
 
    //left column
    for(int i=0; i<m; i++){
        dp[i][0] = 1;
    }
 
    //top row
    for(int j=0; j<n; j++){
        dp[0][j] = 1;
    }
 
    //fill up the dp table
    for(int i=1; i<m; i++){
        for(int j=1; j<n; j++){
            dp[i][j] = dp[i-1][j] + dp[i][j-1];
        }
    }
 
    return dp[m-1][n-1];
}

public static void main(String[] args) {
      
      RoboProblem rb = new RoboProblem();
         System.out.println(rb.uniquePaths(4,4));
       // m.start(0,1,grid);
    }

}

answered May 15 by BlueCoder

Please log in or register to answer this question.

...