Count unique paths in matrix from top left to bottom right (Memoization)

Given m x n matrix, count of all unique possible paths from top left to the bottom right. From each cell, only move right or down is allowed.

Hint

This algorithm uses memoization to improve performance. It's same as the recursive version of Count unique paths in matrix from top left to bottom right, but with a special 'cache' to store results. The 'cache key' is crucial. It's how we identify and store past results. Sometimes we need one key, sometimes multiple keys. We add code to:

# Python implementation
cache = None

def count(m, n):
  if m == 1 or n == 1:
    return 1
  
  global cache
  if not cache:
    cache = [[None for _ in range(n + 1)] for _ in range(m + 1)]

  if not cache[m][n]:
    cache[m][n] = count(m - 1, n) + count(m, n - 1)

  return cache[m][n]

m = 2
n = 2

print(count(m, n))
// Javascript implementation
let cache = null;

function count(m, n) {
  if (m == 1 || n == 1) {
    return 1;
  }

  if (!cache) {
    cache = Array.from(Array(n + 1), () => Array(m + 1));
  }

  if (cache[m][n] === undefined) {
    cache[m][n] = count(m - 1, n) + count(m, n - 1);
  }

  return cache[m][n];
}

const m = 2;
const n = 2;

console.log(count(m, n));