Maximum size of square sub-matrix with all 1s (Tabulation)

Given a binary matrix of size n * m, find out the maximum size of square sub-matrix with all 1s.

Hint

Building upon understanding of Maximum size of square sub-matrix with all 1s (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 search(m):
  cache = [[0] * (len(m[0]) + 1) for _ in range(len(m) + 1)]
  mx = 0

  for i in range(len(m) - 1, -1, -1):
    for j in range(len(m[0]) - 1, -1, -1):
      if m[i][j] == 1:
        cache[i][j] = 1 + min(cache[i][j + 1], cache[i + 1][j], cache[i + 1][j + 1])
        mx = max(mx, cache[i][j])

  return mx

data = [
  [0, 1, 1, 0, 1],
  [1, 1, 0, 1, 0],
  [0, 1, 1, 1, 0],
  [1, 1, 1, 1, 0],
  [1, 1, 1, 1, 1],
  [0, 0, 0, 0, 0]
]

print(search(data))
// Javascript implementation
function search(m) {
  const cache = Array.from(Array(m.length + 1), () => Array(m[0].length + 1).fill(0));
  let max = 0;

  for (let i = m.length - 1; i >= 0 ; i--) {
    for (let j = m[0].length - 1; j >= 0 ; j--) {
      if (m[i][j] == 1) {
        cache[i][j] = 1 + Math.min(cache[i][j + 1], cache[i + 1][j], cache[i + 1][j + 1]);
        max = Math.max(max, cache[i][j])
      }
    }
  }

  return max;
}

const data = [
  [0, 1, 1, 0, 1],
  [1, 1, 0, 1, 0],
  [0, 1, 1, 1, 0],
  [1, 1, 1, 1, 0],
  [1, 1, 1, 1, 1],
  [0, 0, 0, 0, 0]
];

console.log(search(data));