Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: Count all square submatrices made entirely of 1s.

Problem: Count all square submatrices made entirely of 1s.
def count(m):
    R, C = len(m), len(m[0]); tot = 0
    dp = [row[:] for row in m]
    for r in range(R):
        for c in range(C):
            if m[r][c] and r and c:
                dp[r][c] = 1 + min(dp[r-1][c], dp[r][c-1], dp[r-1][c-1])
            tot += dp[r][c]
    return tot
print(count([[0, 1, 1, 1], [1, 1, 1, 1], [0, 1, 1, 1]]))
What is printed?
  1. A. 10
  2. B. 13
  3. C. 15
  4. D. 17

Correct answer: C. 15

dp[r][c] = side of the largest all-1 square ending at (r, c), and that cell also ends exactly dp[r][c] squares (sides 1..dp). The grid has 10 ones (10 squares of side 1), 4 squares of side 2 and 1 of side 3: 15.

More Coding Interview Problems questions

Exams that ask this topic