Skip to main content

221. Maximal Square

/*
* @lc app=leetcode id=221 lang=cpp
*
* [221] Maximal Square
*
* https://leetcode.com/problems/maximal-square/description/
*
* algorithms
* Medium (47.66%)
* Likes: 10401
* Dislikes: 237
* Total Accepted: 759.3K
* Total Submissions: 1.6M
* Testcase Example: '[["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]'
*
* Given an m x n binary matrix filled with 0's and 1's, find the largest
* square containing only 1's and return its area.
*
*
* Example 1:
*
*
* Input: matrix =
* [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
* Output: 4
*
*
* Example 2:
*
*
* Input: matrix = [["0","1"],["1","0"]]
* Output: 1
*
*
* Example 3:
*
*
* Input: matrix = [["0"]]
* Output: 0
*
*
*
* Constraints:
*
*
* m == matrix.length
* n == matrix[i].length
* 1 <= m, n <= 300
* matrix[i][j] is '0' or '1'.
*
*
*/

// @lc code=start
class Solution {
public:
int maximalSquare(vector<vector<char>>& matrix)
{
int m = matrix.size(), n = matrix[0].size();
vector<vector<int>> dp(m, vector<int>(n));
int d = 0;
for (int i = 0; i < m; ++i)
{
for (int j = 0; j < n; ++j)
{
if (i == 0 || j == 0)
{
dp[i][j] = matrix[i][j] - '0';
}
else if (matrix[i][j] == '1')
{
dp[i][j] = min({dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1]}) + 1;
}
d = max(d, dp[i][j]);
}
}
return d * d;
}
};
// @lc code=end
  • T: O(mn)O(m \cdot n)
  • S: O(mn)O(m \cdot n)

2 - Space Improved