Sunday 17 July 2016

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)



 int uniquePaths(int m, int n) {  
   long nr = 1;  
   int t, i, j;  
   if(m > n){  
     t = m;  
     m = n;  
     n = t;  
   }  
   if(m - 1 == 0)  
     return 1;  
   j = m + n - 2;  
   for(i = 1; i <= m - 1; i++){  
     nr = nr * j;  
     j--;  
   }  
   for(i = 1; i <= (m - 1); i++){  
     nr = nr / i;  
   }  
   return nr;  
 }  
Share:

0 comments:

Post a Comment

Contact Me

Name

Email *

Message *

Popular Posts

Blog Archive