Grid Unique Paths

Problem Statement

Given two integers m and n, representing the number of rows and columns of a 2d array named matrix. Return the number of unique ways to go from the top-left cell (matrix[0][0]) to the bottom-right cell (matrix[m-1][n-1]).

Constraints

Allowed Moves:

Example

Input: m = 3, n = 2 Output: 3 Explanation: Starting from (0,0) down(1,0) -> down(2,0) -> right(2,1) down(1,0) -> right(1,1) -> down(2,1) right(0,1) -> down(1,1) -> down(2,1)

Approach (Recursive)

def getNoOfValidPaths(i, j, m, n): if i == m-1 and j == n-1: return 1 elif i >= m or j >= n: return 0 down = getNoOfValidPaths(i+1, j, m, n) right = getNoOfValidPaths(i, j+1, m, n) return down + right

Complexity Analysis

Approach (Dynamic Programming)

def getNoOfValidPathsUsingDP(i, j, m, n, memo): if i == m-1 and j == n-1: return 1 elif i >= m or j >= n: return 0 if (i, j) in memo: return memo[(i, j)] down = getNoOfValidPaths(i+1, j, m, n, memo) right = getNoOfValidPaths(i, j+1, m, n, memo) memo[(i, j)] = down + right return memo[(i, j)]

Complexity Analysis