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

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

Building upon understanding of Count unique paths in matrix from top left to bottom right (Memoization). Pay attention to the cache. Tabulation essentially reconstructs the cache.

Start with the foundation – the base cases, which are the simplest solutions. Then, layer by layer, use the results of the previous layers to calculate the solutions for the next level. This way, we systematically build up the entire solution, avoiding redundant calculations and ensuring efficiency. It is like building a pyramid.

The underlying calculation logic remains fundamentally identical to the original recursive approach, albeit executed in reverse order.

# Python implementation
def count(m, n):
  cache = [[0 for _ in range(n)] for _ in range(m)]

  for i in range(m):
    for j in range(n):
      cache[i][j] = 1 if i == 0 or j == 0 else cache[i - 1][j] + cache[i][j - 1]

  return cache[m - 1][n - 1]

m = 2
n = 2

print(count(m, n))
// Javascript implementation
function count(m, n) {
  const cache = Array.from(Array(m), () => Array(n).fill(0));

  for (let i = 0; i < m; i++) {
    for (let j = 0; j < n; j++) {
      cache[i][j] = (i == 0 || j == 0) ? 1 : cache[i - 1][j] + cache[i][j - 1];
    }
  }

  return cache[m - 1][n - 1];
}

const m = 2;
const n = 2;

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