<p>Given a <code>m * n</code> matrix of ones and zeros, return how many <strong>square</strong> submatrices have all ones.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> matrix =
[
&nbsp; [0,1,1,1],
&nbsp; [1,1,1,1],
&nbsp; [0,1,1,1]
]
<strong>Output:</strong> 15
<strong>Explanation:</strong> 
There are <strong>10</strong> squares of side 1.
There are <strong>4</strong> squares of side 2.
There is  <strong>1</strong> square of side 3.
Total number of squares = 10 + 4 + 1 = <strong>15</strong>.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> matrix = 
[
  [1,0,1],
  [1,1,0],
  [1,1,0]
]
<strong>Output:</strong> 7
<strong>Explanation:</strong> 
There are <b>6</b> squares of side 1.  
There is <strong>1</strong> square of side 2. 
Total number of squares = 6 + 1 = <b>7</b>.
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= arr.length&nbsp;&lt;= 300</code></li>
	<li><code>1 &lt;= arr[0].length&nbsp;&lt;= 300</code></li>
	<li><code>0 &lt;= arr[i][j] &lt;= 1</code></li>
</ul>

class Solution:
    def countSquares(self, matrix: List[List[int]]) -> int:
        # dp(i, j) = 1 + min(below[i][j], right[i][j], dp[i + 1][j + 1]))

        dp = []
        below = []
        right = []
        res = 0
        for i in range(len(matrix) + 1):
            dp.append([0] * (len(matrix[0]) + 1))
            below.append([0] * (len(matrix[0]) + 1))
            right.append([0] * (len(matrix[0]) + 1))

        for i in range(len(matrix)):
            amt_right = 0
            for j in reversed(range(len(matrix[i]))):
                if matrix[i][j] == 1:
                    amt_right += 1
                else: 
                    amt_right = 0
                right[i][j] = amt_right

        for j in range(len(matrix[0])):
            amt_below = 0
            for i in reversed(range(len(matrix))):
                if matrix[i][j] == 1:
                    amt_below += 1
                else: 
                    amt_below = 0
                below[i][j] = amt_below
                

        for i in reversed(range(len(matrix))):
            for j in reversed(range(len(matrix[i]))):
                if matrix[i][j] == 0:
                    continue
                dp[i][j] = 1 + min(dp[i + 1][j + 1], right[i][j] - 1, below[i][j] - 1)
                res += dp[i][j]

        return res
                

        

19700