Open In App

Count all possible paths from source to destination in given 3D array

Last Updated : 15 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given three integers p, q, and r, the task is to count all the possible paths from the cell (0, 0, 0) to cell (p-1, q-1, r-1) in a matrix of size (p, q, r).  Movement is allowed only in three directions, which are along the positive direction of the three axes i.e. from any cell (i, j, k) movement is allowed to cells (i+1, j, k), (i, j+1, k) and (i, j, k+1).

Examples:

Input: p = 1, q = 1, r = 1
Output: 1
Explanation: As the source and destination both are same, there is only one possible way to stay there.

Input: p = 2, q = 2, r = 2
Output: 6
Explanation: The possible paths are :

  • (0, 0, 0) -> (0, 1, 0) -> (0, 1, 1) -> (1, 1, 1)
  • (0, 0, 0) -> (0, 1, 0) -> (1, 1, 0) -> (1, 1, 1)
  • (0, 0, 0) -> (1, 0, 0) -> (1, 1, 0) -> (1, 1, 1)
  • (0, 0, 0) -> (1, 0, 0) -> (1, 0, 1) -> (1, 1, 1)
  • (0, 0, 0) -> (0, 0, 1) -> (0, 1, 1) -> (1, 1, 1)
  • (0, 0, 0) -> (0, 0, 1) -> (1, 0, 1) -> (1, 1, 1)

Using Recursion â€“ O(2^(p+q+r)) Time and O(p+q+r) Space

The recursive approach can be described with three potential moves from a given cell (i, j, k), where we can move to the next cells in three directions: (i+1, j, k), (i, j+1, k), or (i, j, k+1). The recurrence relation can be mathematically defined as:

  • numberOfWays(i, j, k) = numberOfWays(i+1, j, k) + numberOfWays(i, j+1, k) + numberOfWays(i, j, k+1)

Base Case: If the indices reach the last cell, i.e., when i = p-1, j = q-1 and k = r-1, the number of ways is 1: numberOfWays(i, j, k) = 1

C++
// c++ program to Count all possible paths from source
// to destination using recursion

#include <bits/stdc++.h>
using namespace std;

int numberOfWays(int i, int j, int k, int p, int q, int r) {
  
    // Base case: If we have reached the
    // destination (p-1, q-1, r-1), return 1 (valid path)
    if (i == p - 1 && j == q - 1 && k == r - 1)
        return 1;

    int tot = 0;
  
    // move to the next index in the i-dimension
    if (i + 1 < p)
        tot += numberOfWays(i + 1, j, k, p, q, r);

     // move to the next index in the j-dimension
    if (j + 1 < q)
        tot += numberOfWays(i, j + 1, k, p, q, r);

     // move to the next index in the k-dimension
    if (k + 1 < r)
        tot += numberOfWays(i, j, k + 1, p, q, r);

    return tot;
}

int main() {
    int p = 2, q = 2, r = 2;
    int res = numberOfWays(0, 0, 0, p, q, r);
    cout << res <<endl;
    return 0;
}
Java
// Java program to Count all possible paths from source
// to destination using recursion

class GfG {

    static int numberOfWays(int i, int j, int k, int p,
                            int q, int r) {

        // Base case: If we have reached the destination
        // (p-1, q-1, r-1), return 1 (valid path)
        if (i == p - 1 && j == q - 1 && k == r - 1) {
            return 1;
        }

        int tot = 0;

       
        //move to the next index in the i-dimension
        if (i + 1 < p) {
            tot += numberOfWays(i + 1, j, k, p, q, r);
        }

       
        // move to the next index in the j-dimension
        if (j + 1 < q) {
            tot += numberOfWays(i, j + 1, k, p, q, r);
        }

       
        // move to the next index in the k-dimension
        if (k + 1 < r) {
            tot += numberOfWays(i, j, k + 1, p, q, r);
        }

        return tot;
    }

    public static void main(String[] args) {
        int p = 2, q = 2, r = 2;
        int res = numberOfWays(0, 0, 0, p, q, r);
        System.out.println(res);
    }
}
Python
# Python program to Count all possible paths from source
# to destination using recursion

def numberOfWays(i, j, k, p, q, r):
  
    # Base case: If we have reached the
    # destination (p-1, q-1, r-1), return 1 (valid path)
    if i == p - 1 and j == q - 1 and k == r - 1:
        return 1

    total = 0  
    
    # move to the next index in the i-dimension
    if i + 1 < p:
        total += numberOfWays(i + 1, j, k, p, q, r)

    #  move to the next index in the j-dimension
    if j + 1 < q:
        total += numberOfWays(i, j + 1, k, p, q, r)  #

    # move to the next index in the k-dimension
    if k + 1 < r:
        total += numberOfWays(i, j, k + 1, p, q, r)

    return total


if __name__ == "__main__":
    p, q, r = 2, 2, 2
    res = numberOfWays(0, 0, 0, p, q, r)
    print(res)
C#
// C# program to Count all possible paths from source
// to destination using recursion

using System;

class GfG {

    static int numberOfWays(int i, int j, int k, int p,
                            int q, int r) {
      
        // Base case: If we have reached the destination
        // (p-1, q-1, r-1),
        // return 1 (valid path)
        if (i == p - 1 && j == q - 1 && k == r - 1)
            return 1;

        int total = 0;

        // move to the next index in the i-dimension
        if (i + 1 < p)
            total += numberOfWays(i + 1, j, k, p, q, r);

        // move to the next index in the j-dimension
        if (j + 1 < q)
            total += numberOfWays(i, j + 1, k, p, q, r);

        // move to the next index in the k-dimension
        if (k + 1 < r)
            total += numberOfWays(i, j, k + 1, p, q, r);

        return total;
    }

    static void Main(string[] args) {
        int p = 2, q = 2, r = 2;
        int res = numberOfWays(0, 0, 0, p, q, r);
        Console.WriteLine(res);
    }
}
JavaScript
// JavaScript program to Count all possible paths from source
// to destination using recursion
 
function numberOfWays(i, j, k, p, q, r) {
  
    // Base case: If we have reached the destination (p-1,
    // q-1, r-1), return 1 (valid path)
    if (i === p - 1 && j === q - 1 && k === r - 1) {
        return 1;
    }

    let total = 0;

    // move to the next index in the i-dimension
    if (i + 1 < p) {
        total += numberOfWays(i + 1, j, k, p, q, r);
    }

    // move to the next index in the j-dimension
    if (j + 1 < q) {
        total += numberOfWays(i, j + 1, k, p, q, r);
    }

    // move to the next index in the k-dimension
    if (k + 1 < r) {
        total += numberOfWays(i, j, k + 1, p, q, r);
    }

    return total;
}

const p = 2, q = 2, r = 2;
const res = numberOfWays(0, 0, 0, p, q, r);
console.log(res);

Output
6

Using Top-Down DP (Memoization) – O(p*q*r) Time and O(p*q*r) Space

If we notice carefully, we can observe that the above recursive solution holds the following two properties of Dynamic Programming:

1. Optimal Substructure:

The number of unique possible paths to reach the cell (i, j, k) depends on the optimal solutions of the smaller subproblems. Specifically, the number of ways to reach (i, j, k) is determined by the number of ways to reach the adjacent cells (i+1, j, k), (i, j+1, k), and (i, j, k+1). By combining these optimal substructures, we can efficiently calculate the total number of ways to reach the destination cell (p-1, q-1, r-1).

2. Overlapping Subproblems:

When applying a recursive approach to this problem, we observe that many subproblems are computed multiple times, leading to overlapping subproblems. For instance, when calculating the number of paths to a particular cell, say numberOfPaths(3, 3, 3), we may recursively calculate numberOfPaths(3, 2, 3) and numberOfPaths(2, 3, 3). Both of these calculations, in turn, would recursively compute numberOfPaths(2, 2, 3) multiple times—once from numberOfPaths(3, 2, 3) and again from numberOfPaths(2, 3, 3). This redundancy leads to overlapping subproblems.

  • The recursive solution for counting the number of paths involves changing three parameters: i, which represents the current row, j, which represents the current column, and k, which represents the current depth along the third dimension.
  • We need to track all three parameters, so we need to create a 3D array of size p x q x r, where p is the number of rows, q is the number of columns, and r is the number of depths in the matrix.
  • This allows us to store the result for every combination of (i, j, k) where i will range from 0 to p-1, j from 0 to q-1, and k from 0 to r-1.
C++
// c++ program to Count all possible paths from source
// to destination using memoization

#include <bits/stdc++.h>
using namespace std;

int numberOfWays(int i, int j, int k, int p, int q, int r,
                 vector<vector<vector<int>>> &memo) {

    // Base case: If we have reached the
    // destination (p-1, q-1, r-1), return 1 (valid path)
    if (i == p - 1 && j == q - 1 && k == r - 1)
        return 1;

    if (memo[i][j][k] != -1)
        return memo[i][j][k];

    int tot = 0;

    // move to the next index in the i-dimension
    if (i + 1 < p)
        tot += numberOfWays(i + 1, j, k, p, q, r, memo);

     // move to the next index in the j-dimension
    if (j + 1 < q)
        tot += numberOfWays(i, j + 1, k, p, q, r, memo);

      // move to the next index in the k-dimension
    if (k + 1 < r)
        tot += numberOfWays(i, j, k + 1, p, q, r, memo);

    return memo[i][j][k] = tot;
}

int main() {
    int p = 2, q = 2, r = 2;
    vector<vector<vector<int>>> memo =
        vector<vector<vector<int>>>(p, 
                                    vector<vector<int>>(q, vector<int>(r, -1)));
    int res = numberOfWays(0, 0, 0, p, q, r, memo);
    cout << res;

    return 0;
}
Java
// Java program to Count all possible paths from source
// to destination using memoization

class GfG {
 
      static int numberOfWays(int i, int j, int k,
                                   int p, int q, int r,
                                   int[][][] memo) {

        // Base case: If we have reached the destination
        // (p-1, q-1, r-1), return 1 (valid path)
        if (i == p - 1 && j == q - 1 && k == r - 1) {
            return 1;
        }

        if (memo[i][j][k] != -1) {
            return memo[i][j][k];
        }

        int totalWays = 0;

        // If we haven't reached the last index in dimension
        // i, move to the next index in the i-dimension
        if (i + 1 < p) {
            totalWays
                += numberOfWays(i + 1, j, k, p, q, r, memo);
        }

        // If we haven't reached the last index in dimension
        // j, move to the next index in the j-dimension
        if (j + 1 < q) {
            totalWays
                += numberOfWays(i, j + 1, k, p, q, r, memo);
        }

        // If we haven't reached the last index in dimension
        // k, move to the next index in the k-dimension
        if (k + 1 < r) {
            totalWays
                += numberOfWays(i, j, k + 1, p, q, r, memo);
        }

        memo[i][j][k] = totalWays;
        return totalWays;
    }

    public static void main(String[] args) {
        int p = 2, q = 2, r = 2;

        // Initializing memo array with -1 to indicate that
        // no subproblem has been solved yet
        int[][][] memo = new int[p][q][r];
        for (int i = 0; i < p; i++) {
            for (int j = 0; j < q; j++) {
                for (int k = 0; k < r; k++) {
                    memo[i][j][k]
                        = -1;  
                              
                }
            }
        }
        int res =  numberOfWays(0, 0, 0, p, q, r, memo);
        System.out.println(res);
    }
}
Python
# Python program to Count all possible paths from source
# to destination using memoization

def numberOfWays(i, j, k, p, q, r, memo):
  
    # Base case: If we have reached the 
    # destination (p-1, q-1, r-1), return 1 (valid path)
    if i == p - 1 and j == q - 1 and k == r - 1:
        return 1
    
    # If the result is already computed,
    # return the stored value
    if memo[i][j][k] != -1:
        return memo[i][j][k]
    
    totalWays = 0
    
    # move to the next index in the i-dimension
    if i + 1 < p:
        totalWays += numberOfWays(i + 1, j, k, p, q, r, memo)
    
    # move to the next index in the j-dimension
    if j + 1 < q:
        totalWays += numberOfWays(i, j + 1, k, p, q, r, memo)
    
    # move to the next index in the k-dimension
    if k + 1 < r:
        totalWays += numberOfWays(i, j, k + 1, p, q, r, memo)
    
    # Store the result in the memoization array
    memo[i][j][k] = totalWays
    return totalWays

 
p, q, r = 2, 2, 2
memo = [[[ -1 for _ in range(r)] for _ in range(q)] for _ in range(p)]
res = numberOfWays(0, 0, 0, p, q, r, memo)
print(res)
C#
// C# program to Count all possible paths from source
// to destination using memoization

using System;

class  GfG {
   
    static int numberOfWays(int i, int j, int k, int p, 
                            int q, int r, int[,,] memo) {
       
        // Base case: If we have reached the destination 
      // (p-1, q-1, r-1), return 1 (valid path)
        if (i == p - 1 && j == q - 1 && k == r - 1)
            return 1;

        // If the result is already computed, 
      // return the stored value
        if (memo[i, j, k] != -1)
            return memo[i, j, k];

        int totalWays = 0;

      // move to the next index in the i-dimension
        if (i + 1 < p)
            totalWays += numberOfWays(i + 1, j, k, p, q, r, memo);

       // move to the next index in the j-dimension
        if (j + 1 < q)
            totalWays += numberOfWays(i, j + 1, k, p, q, r, memo);
 
       // move to the next index in the k-dimension
        if (k + 1 < r)
            totalWays += numberOfWays(i, j, k + 1, p, q, r, memo);

        // Store the result in the memoization array
        memo[i, j, k] = totalWays;

        return totalWays;
    }

    static void Main() {
        int p = 2, q = 2, r = 2;

      
        int[,,] memo = new int[p, q, r];
        for (int i = 0; i < p; i++)
            for (int j = 0; j < q; j++)
                for (int k = 0; k < r; k++)
                    memo[i, j, k] = -1;
      int res = numberOfWays(0, 0, 0, p, q, r, memo);
        Console.WriteLine(res);
    }
}
JavaScript
// JavaScript program to Count all possible paths from
// source to destination using memoization

function numberOfWays(i, j, k, p, q, r, memo) {

    // Base case: If we have reached the destination
    // (p-1, q-1, r-1), return 1 (valid path)
    if (i === p - 1 && j === q - 1 && k === r - 1) {
        return 1;
    }

    // If the result is already computed,
    // return the stored value
    if (memo[i][j][k] !== -1) {
        return memo[i][j][k];
    }

    let totalWays = 0;

    // move to the next index in the i-dimension
    if (i + 1 < p) {
        totalWays
            += numberOfWays(i + 1, j, k, p, q, r, memo);
    }

    // move to the next index in the j-dimension
    if (j + 1 < q) {
        totalWays
            += numberOfWays(i, j + 1, k, p, q, r, memo);
    }

    // move to the next index in the k-dimension
    if (k + 1 < r) {
        totalWays
            += numberOfWays(i, j, k + 1, p, q, r, memo);
    }

    // Store the result in the memoization array
    memo[i][j][k] = totalWays;
    return totalWays;
}

const p = 2, q = 2, r = 2;

const memo
    = Array.from({length : p},
                 () => Array.from({length : q},
                                  () => Array(r).fill(-1)));

const res = numberOfWays(0, 0, 0, p, q, r, memo);

console.log(res);

Output
6

Using Bottom-Up DP (Tabulation) – O(p*q*r) Time and O(p*q*r) Space

The approach here is similar to the recursive solution but, instead of breaking down the problem recursively, we use an iterative approach to build up the solution from the base cases in a bottom-up manner.
To solve the 3D path problem iteratively, we maintain a dp[i][j][k] table where each entry dp[i][j][k] stores the count of all possible paths to reach the cell (i, j, k).

Base Case: For i == p-1 and j == q-1 and k == r-1 , dp[i][j][k] = 1

Recursive Case: dp[i][j][k] = dp[i-1][j][k] + dp[i][j-1][k] + dp[i][j][k-1];

C++
// C++ program to Count all possible paths from source
// to destination using tabulation

#include <bits/stdc++.h>
using namespace std;

int numberOfWays(int p, int q, int r) {
    vector<vector<vector<int>>> dp
      (p, vector<vector<int>>(q, vector<int>(r)));

    // Initialising dp
    dp[0][0][0] = 1;

    for (int i = 0; i < p; ++i) {
        for (int j = 0; j < q; ++j) {
            for (int k = 0; k < r; ++k) {
                if (i == 0 and j == 0 and k == 0) {
                    continue;
                }
                dp[i][j][k] = 0;
                if (i - 1 >= 0) {
                    dp[i][j][k] += dp[i - 1][j][k];
                }
                if (j - 1 >= 0) {
                    dp[i][j][k] += dp[i][j - 1][k];
                }
                if (k - 1 >= 0) {
                    dp[i][j][k] += dp[i][j][k - 1];
                }
            }
        }
    }

    return dp[p - 1][q - 1][r - 1];
}

int main() {
  
    int p = 2, q = 2, r = 2;
    int res = numberOfWays(p, q, r);
    cout << res;
}
Java
// Java program to Count all possible paths from source
// to destination using memoization

import java.util.*;

class  GfG {

      static int numberOfWays(int p, int q, int r) {
        int[][][] dp = new int[p][q][r];

        // Initializing dp for the starting cell
        dp[0][0][0] = 1;

        for (int i = 0; i < p; ++i) {
            for (int j = 0; j < q; ++j) {
                for (int k = 0; k < r; ++k) {
                  
                    // Skip the starting cell as it's
                    // already initialized
                    if (i == 0 && j == 0 && k == 0) {
                        continue;
                    }
                    dp[i][j][k] = 0;

                    // Check and add ways from the previous
                    // cell in each dimension
                    if (i - 1 >= 0) {
                        dp[i][j][k] += dp[i - 1][j][k];
                    }
                    if (j - 1 >= 0) {
                        dp[i][j][k] += dp[i][j - 1][k];
                    }
                    if (k - 1 >= 0) {
                        dp[i][j][k] += dp[i][j][k - 1];
                    }
                }
            }
        }

        
        return dp[p - 1][q - 1][r - 1];
    }

    public static void main(String[] args) {
        int p = 2, q = 2, r = 2;
        int res = numberOfWays(p, q, r);
        System.out.println(res);
    }
}
Python
# Python program to Count all possible paths from source
# to destination using memoization

def numberOfWays(p, q, r):
  
    # Initialize a 3D dp array with zeros
    dp = [[[0 for _ in range(r)] for _ in range(q)] for _ in range(p)]

    # Starting point
    dp[0][0][0] = 1

    for i in range(p):
        for j in range(q):
            for k in range(r):
              
                # Skip the starting cell
                if i == 0 and j == 0 and k == 0:
                    continue

                # Calculate the number of ways by 
                # summing valid neighboring cells
                if i > 0:
                    dp[i][j][k] += dp[i - 1][j][k]
                if j > 0:
                    dp[i][j][k] += dp[i][j - 1][k]
                if k > 0:
                    dp[i][j][k] += dp[i][j][k - 1]

   
    return dp[p - 1][q - 1][r - 1]

p, q, r = 2, 2, 2
res = numberOfWays(p, q, r)
print(res)
C#
// C# program to Count all possible paths from source
// to destination using memoization

using System;

class GfG {
    static int numberOfWays(int p, int q, int r) {
       
        // Initialize a 3D dp array with zeros
        int[, , ] dp = new int[p, q, r];

        // Starting point
        dp[0, 0, 0] = 1;

        for (int i = 0; i < p; i++) {
            for (int j = 0; j < q; j++) {
                for (int k = 0; k < r; k++) {
                  
                    // Skip the starting cell
                    if (i == 0 && j == 0 && k == 0) {
                        continue;
                    }

                    // Calculate the number of ways by
                    // summing valid neighboring cells
                    if (i > 0) {
                        dp[i, j, k] += dp[i - 1, j, k];
                    }
                    if (j > 0) {
                        dp[i, j, k] += dp[i, j - 1, k];
                    }
                    if (k > 0) {
                        dp[i, j, k] += dp[i, j, k - 1];
                    }
                }
            }
        }

        // Return the number of ways to reach the
        // destination cell
        return dp[p - 1, q - 1, r - 1];
    }

    static void Main() {
        int p = 2, q = 2, r = 2;
        int res = numberOfWays(p, q, r);
        Console.WriteLine(res);
    }
}
JavaScript
// JavaScript program to Count all possible paths from
// source to destination using memoization

function numberOfWays(p, q, r) {

    // Initialize a 3D dp array with zeros
    const dp = Array.from(
        {length : p},
        () => Array.from({length : q},
                         () => Array(r).fill(0)));

    // Starting point
    dp[0][0][0] = 1;

    // Fill the dp array in a bottom-up manner
    for (let i = 0; i < p; i++) {
        for (let j = 0; j < q; j++) {
            for (let k = 0; k < r; k++) {
                // Skip the starting cell
                if (i === 0 && j === 0 && k === 0)
                    continue;

                // Calculate the number of ways by summing
                // valid neighboring cells
                if (i > 0)
                    dp[i][j][k] += dp[i - 1][j][k];
                if (j > 0)
                    dp[i][j][k] += dp[i][j - 1][k];
                if (k > 0)
                    dp[i][j][k] += dp[i][j][k - 1];
            }
        }
    }
    return dp[p - 1][q - 1][r - 1];
}

 
const p = 2, q = 2, r = 2;
const res = numberOfWays(p, q, r)
console.log(res);

Output
6

Using Space Optimized DP – O(p*q*r) Time and O(q*r) Space

In previous approach we can see that the dp[i][j][k] is depend upon dp[i – 1][j][k], dp[i][j – 1][k] and dp[i][j][k – 1] so we can convert 3d matrix into current and previous 2d matrix where i-1 refer to previous and i refer to current.

  • Create two 2d matrix refer to previous and current matrix.
  • Initialize both matrix starting point with 1.
  • Now the approach is same as the previous code but we have to only convert dp[i] to current and dp[i-1] to previous.
C++
// c++ program to Count all possible paths from source
// to destination Using Space Optimization

#include <bits/stdc++.h>
using namespace std;

int numberOfWays(int p, int q, int r) {

    vector<vector<int>> curr(q, vector<int>(r, 0));
    vector<vector<int>> prev(q, vector<int>(r, 0));

    // Initialising dp
    prev[0][0] = 1;
    curr[0][0] = 1;

    for (int i = 0; i < p; ++i) {
        for (int j = 0; j < q; ++j) {
            for (int k = 0; k < r; ++k) {
                if (i == 0 && j == 0 && k == 0) {
                    continue;
                }
                curr[j][k] = 0;
                if (i - 1 >= 0) {
                    curr[j][k] += prev[j][k];
                }
                if (j - 1 >= 0) {
                    curr[j][k] += curr[j - 1][k];
                }
                if (k - 1 >= 0) {
                    curr[j][k] += curr[j][k - 1];
                }
            }
        }
        prev = curr;
    }

    return curr[q - 1][r - 1];
}

int main() {

    int p = 2, q = 2, r = 2;
    int res = numberOfWays(p, q, r);
    cout << res;
}
Java
// Java program to Count all possible paths from source
// to destination Using Space Optimization

import java.util.Arrays;

class GfG {

    static int numberOfWays(int p, int q, int r) {
        int[][] curr = new int[q][r];
        int[][] prev = new int[q][r];

        // Initializing dp
        prev[0][0] = 1;
        curr[0][0] = 1;

        for (int i = 0; i < p; ++i) {
            for (int j = 0; j < q; ++j) {
                for (int k = 0; k < r; ++k) {
                    if (i == 0 && j == 0 && k == 0) {
                        continue;
                    }
                    curr[j][k] = 0;
                    if (i - 1 >= 0) {
                        curr[j][k] += prev[j][k];
                    }
                    if (j - 1 >= 0) {
                        curr[j][k] += curr[j - 1][k];
                    }
                    if (k - 1 >= 0) {
                        curr[j][k] += curr[j][k - 1];
                    }
                }
            }
          
            // Copy curr to prev for the next layer
            for (int j = 0; j < q; ++j) {
                System.arraycopy(curr[j], 0, prev[j], 0, r);
            }
        }

        return curr[q - 1][r - 1];
    }

    public static void main(String[] args) {
        int p = 2, q = 2, r = 2;
        int res = numberOfWays(p, q, r);
        System.out.println(res);
    }
}
Python
# Python program to Count all possible paths from source
# to destination Using Space Optimization
 
def numberOfWays(p, q, r):
  
    # Initialize the 2D arrays for curr and prev
    curr = [[0] * r for _ in range(q)]
    prev = [[0] * r for _ in range(q)]

    # Initializing dp
    prev[0][0] = 1
    curr[0][0] = 1

    for i in range(p):
        for j in range(q):
            for k in range(r):
                if i == 0 and j == 0 and k == 0:
                    continue
                curr[j][k] = 0
                if i - 1 >= 0:
                    curr[j][k] += prev[j][k]
                if j - 1 >= 0:
                    curr[j][k] += curr[j - 1][k]
                if k - 1 >= 0:
                    curr[j][k] += curr[j][k - 1]

        # Copy curr to prev for the next layer
        for j in range(q):
            prev[j] = curr[j][:]

    return curr[q - 1][r - 1]


p = 2
q = 2
r = 2
res = numberOfWays(p, q, r)
print(res)
C#
// C# program to Count all possible paths from source
// to destination Using Space Optimization

using System;

class  GfG {
    static int numberOfWays(int p, int q, int r) {
      
        // Initialize the 2D arrays for curr and prev
        int[, ] curr = new int[q, r];
        int[, ] prev = new int[q, r];

        // Initializing dp
        prev[0, 0] = 1;
        curr[0, 0] = 1;

        for (int i = 0; i < p; i++) {
            for (int j = 0; j < q; j++) {
                for (int k = 0; k < r; k++) {
                    if (i == 0 && j == 0 && k == 0) {
                        continue;
                    }
                    curr[j, k] = 0;
                    if (i - 1 >= 0) {
                        curr[j, k] += prev[j, k];
                    }
                    if (j - 1 >= 0) {
                        curr[j, k] += curr[j - 1, k];
                    }
                    if (k - 1 >= 0) {
                        curr[j, k] += curr[j, k - 1];
                    }
                }
            }

            // Copy curr to prev for the next layer
            for (int j = 0; j < q; j++) {
                for (int k = 0; k < r; k++) {
                    prev[j, k] = curr[j, k];
                }
            }
        }

        return curr[q - 1, r - 1];
    }

    static void Main() {
        int p = 2, q = 2, r = 2;
        int res = numberOfWays(p, q, r);
        Console.WriteLine(res);
    }
}
JavaScript
// JavaScript program to Count all possible paths from
// source to destination Using Space Optimization

function numberOfWays(p, q, r) {

    // Initialize the 2D arrays for curr and prev
    let curr
        = Array.from({length : q}, () => Array(r).fill(0));
    let prev
        = Array.from({length : q}, () => Array(r).fill(0));

    // Initializing dp
    prev[0][0] = 1;
    curr[0][0] = 1;

    for (let i = 0; i < p; i++) {
        for (let j = 0; j < q; j++) {
            for (let k = 0; k < r; k++) {
                if (i === 0 && j === 0 && k === 0) {
                    continue;
                }
                curr[j][k] = 0;
                if (i - 1 >= 0) {
                    curr[j][k] += prev[j][k];
                }
                if (j - 1 >= 0) {
                    curr[j][k] += curr[j - 1][k];
                }
                if (k - 1 >= 0) {
                    curr[j][k] += curr[j][k - 1];
                }
            }
        }

        // Copy curr to prev for the next iteration
        for (let j = 0; j < q; j++) {
            for (let k = 0; k < r; k++) {
                prev[j][k] = curr[j][k];
            }
        }
    }

    return curr[q - 1][r - 1];
}

 
let p = 2, q = 2, r = 2;
let res = numberOfWays(p, q, r);
console.log(res);  

Output
6


Next Article

Similar Reads