<p>Given an <code>m x n</code> binary <code>matrix</code> filled with <code>0</code>&#39;s and <code>1</code>&#39;s, <em>find the largest square containing only</em> <code>1</code>&#39;s <em>and return its area</em>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/11/26/max1grid.jpg" style="width: 400px; height: 319px;" />
<pre>
<strong>Input:</strong> matrix = [[&quot;1&quot;,&quot;0&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;],[&quot;1&quot;,&quot;0&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;],[&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;],[&quot;1&quot;,&quot;0&quot;,&quot;0&quot;,&quot;1&quot;,&quot;0&quot;]]
<strong>Output:</strong> 4
</pre>

<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/11/26/max2grid.jpg" style="width: 165px; height: 165px;" />
<pre>
<strong>Input:</strong> matrix = [[&quot;0&quot;,&quot;1&quot;],[&quot;1&quot;,&quot;0&quot;]]
<strong>Output:</strong> 1
</pre>

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

<pre>
<strong>Input:</strong> matrix = [[&quot;0&quot;]]
<strong>Output:</strong> 0
</pre>

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

<ul>
	<li><code>m == matrix.length</code></li>
	<li><code>n == matrix[i].length</code></li>
	<li><code>1 &lt;= m, n &lt;= 300</code></li>
	<li><code>matrix[i][j]</code> is <code>&#39;0&#39;</code> or <code>&#39;1&#39;</code>.</li>
</ul>

from functools import cache

class Solution:
    def maximalSquare(self, matrix: List[List[str]]) -> int:

        m, n = len(matrix), len(matrix[0])
        answer = [0]

        @cache
        def dp(i, j):
            # size of the largest square anchored at cell i, j
            # print(i, j)
            
            # base case
            if i == 0 or j == 0:
                answer[0] = max(answer[0], int(matrix[i][j]))
                return int(matrix[i][j])
            
            # can we extend?
            diagonal = dp(i-1, j-1)
            up = dp(i-1, j)
            left = dp(i, j-1)
            # print(f'at {(i, j)}', diagonal, up, left)
            if matrix[i][j] == "1" and (diagonal == up == left):
                # print('can extend')
                # print(f'dp{(i, j)} = {1 + diagonal}')
                answer[0] = max(answer[0], 1 + diagonal)
                return 1 + diagonal
            else:
                
                if matrix[i][j] == "1":
                    # print(f'dp{(i, j)} = {1 + min(diagonal, up, left)}')
                    answer[0] = max(answer[0], 1 + min(diagonal, up, left))
                    return 1 + min(diagonal, up, left)
                else:
                    return 0

        for i in range(m):
            dp(i, 0)

        for j in range(n):
            dp(0, j)
            
        _ = dp(m-1, n-1)
        return answer[0] ** 2
               
58075