Count Square Submatrices with All Ones

Given a m * n matrix of ones and zeros, return how many square submatrices have all ones.

30:00

Count Square Submatrices with All Ones
medium
Free written solution
Topics
Companies

Given a m * n matrix of ones and zeros, return how many square submatrices have all ones.

Example 1:
Input: {"matrix":[[0,1,1,1],[1,1,1,1],[0,1,1,1]]}
Output: 15
Constraints:
  • 1≤arr.length≤3001 \leq \text{arr.length} \leq 300

  • 1≤arr[0].length≤3001 \leq \text{arr}[0]\text{.length} \leq 300

  • 0≤arr[i][j]≤10 \leq \text{arr}[i][j] \leq 1

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"matrix":[[0,1,1,1],[1,1,1,1],[0,1,1,1]]}

dp[i][j] = side of the largest all-ones square whose bottom-right corner is cell (i, j). It also equals how many squares end there.

■ current

■ up

■ left

■ diagonal

■ squares ending here

0

1

1

1

1

1

1

1

0

1

1

1

total = 0

Variables
VariableValue
m3
n4
total0
DepthFunction Call
Stack empty
0/14