<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 {
public:
    int dp[301][301];
    int dfs(vector<vector<int>>& A, int i, int j) {
        if(i < 0 || j < 0 || i >= A.size() || j >= A[0].size() || A[i][j] != 1)
            return 0;
        if(dp[i][j] != -1)
            return dp[i][j];
        int ans = 1;
        int l = dfs(A, i, j + 1), r = dfs(A, i + 1, j), t = dfs(A, i + 1, j + 1);
        ans = 1 + min(l, min(r, t));
        return dp[i][j] = ans;
    }
    
    int countSquares(vector<vector<int>>& A) {
        int ans = 0;
        int n = A.size(), m = A[0].size();
        vector<vector<int>> vis(n, vector<int>(m, 0));
        memset(dp, -1, sizeof dp);
        for(int i = 0; i < A.size(); i++) {
            for(int j = 0; j < A[i].size(); j++) {
                if(A[i][j]) {
                    int sz = dfs(A, i, j); 
                    ans += sz;
                }
            }
        }
        return ans;
    }
};
29600