|
| 1 | +/* |
| 2 | +Given a M X N matrix with your initial position at the top-left cell, find the number of possible unique paths to reach the bottom-right cell of the matrix from the initial position. |
| 3 | + |
| 4 | +Note: Possible moves can be either down or right at any point in time, i.e., we can move to matrix[i+1][j] or matrix[i][j+1] from matrix[i][j]. |
| 5 | + |
| 6 | +Input: |
| 7 | +The first line contains an integer T, depicting the total number of test cases. Then following T lines contain two integers M and N depicting the size of the grid. |
| 8 | + |
| 9 | +Output: |
| 10 | +Print the number of unique paths to reach the bottom-right cell from the top-left cell. |
| 11 | + |
| 12 | +Expected Time Complexity: O(M*N). |
| 13 | +Expected Auxiliary Space: O(M*N). |
| 14 | + |
| 15 | +Constraints: |
| 16 | +1 ≤ T ≤ 30 |
| 17 | +1 ≤ M ≤ 20 |
| 18 | +1 ≤ N ≤ 20 |
| 19 | + |
| 20 | +Example: |
| 21 | +Input: |
| 22 | +2 |
| 23 | +2 2 |
| 24 | +3 4 |
| 25 | + |
| 26 | +Output: |
| 27 | +2 |
| 28 | +10 |
| 29 | + |
| 30 | +Example: |
| 31 | +Testcase 1: |
| 32 | +There are only two unique paths to reach the end of the matrix of size two from the starting cell of the matrix. |
| 33 | +*/ |
| 34 | + |
| 35 | +/*package whatever //do not write package name here */ |
| 36 | + |
| 37 | +import java.util.*; |
| 38 | +import java.lang.*; |
| 39 | +import java.io.*; |
| 40 | + |
| 41 | +class GFG { |
| 42 | + public static void main (String[] args) { |
| 43 | + //code |
| 44 | + Scanner in = new Scanner(System.in); |
| 45 | + int t = in.nextInt(); |
| 46 | + while(t > 0) |
| 47 | + { |
| 48 | + int m = in.nextInt(); |
| 49 | + int n = in.nextInt(); |
| 50 | + |
| 51 | + System.out.println(countNumberUniquePath(m,n)); |
| 52 | + t--; |
| 53 | + } |
| 54 | + } |
| 55 | + static int countNumberUniquePath(int m, int n) |
| 56 | + { |
| 57 | + |
| 58 | + if(m == 0) |
| 59 | + return 0; |
| 60 | + |
| 61 | + int[][] path = new int[m][n]; |
| 62 | + for(int i = 0; i<m; i++) |
| 63 | + path[i][0] = 1; |
| 64 | + for(int i = 0; i<n; i++) |
| 65 | + path[0][i] = 1; |
| 66 | + |
| 67 | + for(int i = 1; i < m ; i++) |
| 68 | + { |
| 69 | + for(int j = 1; j<n ; j++) |
| 70 | + { |
| 71 | + path[i][j] = path[i-1][j] + path[i][j-1] ; |
| 72 | + } |
| 73 | + } |
| 74 | + return path[m-1][n-1]; |
| 75 | + } |
| 76 | +} |
0 commit comments