Unique Paths

Updated on 02 July, 2025
Unique Paths header image

Problem Statement

In this problem, we encounter a robot situated at the top-left corner of an m x n grid. The goal for the robot is to traverse to the bottom-right corner of this grid. However, the robot has limited movement options; it can only move either to the right or downwards at each step. Given these two dimensions, m and n, the task is to determine all possible unique paths from the top-left to the bottom-right corner of the grid. The solutions need to fit within computational limits, specifically ensuring that the number of paths does not exceed 2 x 10^9.

Examples

Example 1

Input:

m = 3, n = 7

Output:

28

Example 2

Input:

m = 3, n = 2

Output:

3

Explanation:

From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1. Right -> Down -> Down
2. Down -> Down -> Right
3. Down -> Right -> Down

Constraints

  • 1 <= m, n <= 100

Approach and Intuition

To solve this problem, we can use the concept of combinatory mathematics or dynamic programming.

  • Combinatory Approach:

    1. Realize that any path from the top-left corner to the bottom-right corner in an m x n grid consists of exactly m-1 moves down and n-1 moves right, irrespective of order.
    2. The problem then reduces to finding the number of unique ways to rearrange m-1 downs and n-1 rights.
    3. This can be solved using combinations: C(m+n-2, m-1) or C(m+n-2, n-1), where C(n, k) represents the number of ways to choose k items from n items without regard to order.
  • Dynamic Programming Approach:

    1. Use a 2D array dp where dp[i][j] represents the number of ways to reach cell (i, j) from the top-left corner (0,0).
    2. Initialize dp[0][0] to 1 since there's only one way to be at the starting position.
    3. For each cell (i, j), the robot could have moved from the left (i, j-1) or from above (i-1, j).
    4. Thus, the value of dp[i][j] is the sum of dp[i-1][j] and dp[i][j-1].
    5. The value in dp[m-1][n-1] will give the total number of unique paths from the top-left to the bottom-right corner.

Examples Explained:

  • In the first example (m = 3, n = 7):

    • The dynamic programming approach would create a 3 x 7 matrix and iteratively fill up the matrix to find 28 unique paths.
    • Combinatorially, C(3+7-2, 3-1) = C(8, 2) = 28 unique paths.
  • In the second example (m = 3, n = 2), evaluating DP matrix or combinatorics alike, we'd compute C(3+2-2, 3-1) = C(3, 2) = 3 possible paths, enumerated in the explanation provided.

Solutions

  • C++
  • Java
  • C
  • JavaScript
  • Python
cpp
class Solution {
public:
    int countPaths(int rows, int cols) {
        vector<vector<int>> grid(rows, vector<int>(cols, 1));
        for (int row = 1; row < rows; row++) {
            for (int col = 1; col < cols; col++) {
                grid[row][col] = grid[row - 1][col] + grid[row][col - 1];
            }
        }
        return grid[rows - 1][cols - 1];
    }
};

The problem "Unique Paths" investigates the number of distinct routes one can take to travel from the top-left corner to the bottom-right corner of a grid, using only rightward and downward movements. The provided C++ solution approaches this combinatorial problem using dynamic programming to optimize the computations.

The implementation details involve:

  • Creating a 2D vector named grid with dimensions corresponding to the number of rows and columns in the grid. Initially, all elements in the grid are set to 1, representing there's at least one way to get to each of those cells either directly from the left (first row) or from above (first column).
  • Iterating over the grid starting from the second row and second column, the value of each cell is updated to the sum of the paths leading to the cell from above (grid[row - 1][col]) and from the left (grid[row][col - 1]). This sum represents all unique paths to that cell.
  • Finally, the value at the bottom-right corner of the grid (grid[rows - 1][cols - 1]) gives the total number of unique paths from the top-left corner to the bottom-right corner.

This solution efficiently calculates the paths with a time complexity of O(rows*cols), which is optimal for this problem. Ensure to include headers <vector> for utilizing the vector container in the C++ solution.

java
public class Solution {
    public int countPaths(int rows, int cols) {
        long result = 1;
        for (int j = cols; j < (rows + cols - 1); j++) {
            result *= j;
            result /= (j - cols + 1);
        }
        return (int) result;
    }
}

This solution calculates the number of unique paths in a grid from the top-left corner to the bottom-right corner using a dynamic programming approach. It takes the dimensions of the grid as input parameters, specifically the rows and cols.

The method countPaths initializes a result variable to 1. It then uses a loop to iterate through possible paths. Inside the loop, the result is multiplied by the current index j (starting from cols and going up to rows + cols - 1). The result is then divided by (j - cols + 1). This formula efficiently calculates the combinations needed for moving right and down through the grid without exceeding grid boundaries.

Finally, the method returns the computed number of unique paths as an integer by casting the result to int. This solution leverages mathematical combination logic to solve the problem, providing a performance beneficial especially for larger grids.

c
int pathCount(int rows, int cols) {
    int grid[rows][cols];
    for (int row = 0; row < rows; row++) {
        for (int col = 0; col < cols; col++) {
            if (row == 0 || col == 0) {
                grid[row][col] = 1;
            } else {
                grid[row][col] = grid[row - 1][col] + grid[row][col - 1];
            }
        }
    }
    return grid[rows - 1][cols - 1];
}

The provided solution in C calculates the number of unique paths in a grid from the top-left corner to the bottom-right corner. The grid size is determined by rows and cols, representing the number of rows and columns, respectively.

  • Initialize a 2D array grid with dimensions equivalent to rows and cols.
  • Iterate over each cell in the grid using nested loops:
    • Set the value of each cell in the first row or first column to 1 because there's only one path to each of these cells directly from the start.
  • For other cells not in the first row or column, compute the number of paths by adding the number of paths from the cell directly above and the cell directly to the left. This utilizes the dynamic programming paradigm where the value at each cell represents the number of ways to reach that cell.
  • The final cell grid[rows - 1][cols - 1] holds the result, which is the total number of unique paths from top-left to bottom-right of the grid.

This approach ensures an efficient calculation using a bottom-up method, leveraging previously computed values to build up the solution.

js
var findPaths = function(rows, cols) {
    return computeFactorial(rows + cols - 2) / computeFactorial(cols - 1) / computeFactorial(rows - 1);
};
function computeFactorial(num) {
    let product = 1;
    for (let j = 2; j <= num; j++) {
        product *= j;
    }
    return product;
}

The solution for calculating the number of unique paths on a grid provided in JavaScript utilizes the mathematical concept of combinations. Here, you find the number of paths from the top-left to the bottom-right corner of a grid (without backtracking) by computing the combination:

[ \text{Paths} = \frac{(rows + cols - 2)!}{(cols - 1)! \times (rows - 1)!} ]

  • Start by defining the function findPaths that takes two arguments: rows and cols.
  • Calculate the factorial of (rows + cols - 2), (cols - 1), and (rows - 1) using the helper function computeFactorial.
  • The computeFactorial function computes the factorial of a number iteratively. Initialize a variable product to 1 and multiply it by each integer up to the number for which the factorial is desired.

The overall computational efficiency is centered on the factorial calculation, with iterative multiplication up to the specified number, making the approach straightforward and optimal for small grids. For larger grids or numerous calculations, consider optimizing or using more efficient algorithms to handle large numbers due to possible integer overflow or performance issues.

python
from math import factorial
    
class PathsFinder:
    def calculatePaths(self, rows: int, cols: int) -> int:
        return factorial(rows + cols - 2) // factorial(cols - 1) // factorial(rows - 1)

Problem Summary: Unique Paths

The aim is to determine the number of unique paths on a grid from the top-left corner to the bottom-right corner, moving only down or right at any step.

Solution Breakdown:

  • The user has defined a class PathsFinder in Python.
  • The function inside the class, calculatePaths, takes two parameters: rows and cols. These represent the number of rows and columns in the grid, respectively.
  • The solution uses the combinatorial approach to solve the problem where the unique paths can be calculated using factorials. Specifically, it calculates the number of permutations of moving (rows-1) steps down and (cols-1) steps right.
  • The formula utilized is (rows + cols - 2)! / ((cols - 1)! * (rows - 1)!).
  • Python's math.factorial function is used for computing factorial values efficiently.

Usage: Create an instance of PathsFinder and call the calculatePaths function with specific rows and cols values to get the number of unique paths.

For instance, initializing path_finder = PathsFinder() and calling path_finder.calculatePaths(3, 3) will return the number of unique paths for a 3x3 grid.

Comments

No comments yet.