Wednesday, September 29, 2021

Maneuvering a Cave Problem

Problem Description 
The task is to count all the possible paths from top left to bottom right of a m x n matrix with the constraints that from each cell you can either move only to right or down. 

Input: 
First line consists of T test cases. First line of every test case consists of N and M, denoting the number of rows and number of columns respectively. 

Output: 
Single line output i.e count of all the possible paths from top left to bottom right of a m x n matrix.. 

Constraints: 
1<=T<=100 
1<=N<=100 
1<=M<=100 

SOLUTION (JAVA): 
import java.util.Scanner;
public class MyClass {
    static int count =0,m,n;
    public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      m= sc.nextInt();
      n= sc.nextInt();
      findWays(1,1);
      System.out.println(count);
    }
    
    static void findWays(int i, int j) {
        if(i>m || j>n)
            return;
        if(i==m && j==n){
            count++;
        }
        findWays(i, j+1);
        findWays(i+1,j);
    }
}

SOLUTION (C): 
#include <stdio.h>

int getPaths(int i, int j, int m, int n){
    if(i==m && j==n)
        return 1;
        
    if(i>m || j>n)
        return 0;
    
    return getPaths(i+1,j,m,n)+ getPaths(i,j+1,m,n);
}

int main()
{
    int m,n,i,j;
    scanf("%d %d", &m, &n);
    printf("total paths are : %d", getPaths(0,0,m-1,n-1));
    return 0;
}