<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>

"""
0 1 1 1 
1 1 1 1
0 1 1 1

TC: ? (Brute Force)





"""

class Solution:
    def countSquares(self, matrix: List[List[int]]) -> int:
        if not matrix:
            return 0

        n, m = len(matrix), len(matrix[0])
        sum_grid = [[0]*m for _ in range(n)]

        # Precompute sum_grid, value of each cell represent sum of values
        # in rectangle starting from 0,0  to that cell (x,y)
        for i in range(n):
            for j in range(m):
                sum_val = matrix[i][j]
                
                if i-1 >= 0:
                    sum_val += sum_grid[i-1][j]
                
                if j-1 >= 0:
                    sum_val += sum_grid[i][j-1]
                
                # Subtract diagonal
                if i-1 >= 0 and j-1 >= 0:
                    sum_val -= sum_grid[i-1][j-1]
                
                sum_grid[i][j] = sum_val

        print(sum_grid)
        
        # Check for every possible size of square.
        result = 0
        for size in range(1, min(n,m)+1):
            for x in range(n):
                for y in range(m):
                    top_corner_x, top_corner_y = x - size, y - size
                    temp = sum_grid[x][y]
                    if top_corner_x >= 0:
                        temp -= sum_grid[top_corner_x][y]
                    if top_corner_y >= 0:
                        temp -= sum_grid[x][top_corner_y]
                    
                    if top_corner_x >= 0 and top_corner_y >= 0:
                        temp += sum_grid[top_corner_x][top_corner_y]
                    
                    if temp == (size*size):
                        result += 1

        
        return result
        
22000