Skip to content

Commit 3ebe288

Browse files
authored
Create 0221-maximal-square.cpp
1 parent 9218619 commit 3ebe288

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

cpp/0221-maximal-square.cpp

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/*
2+
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.
3+
4+
Ex. Input: matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
5+
Output: 4
6+
7+
Time : O(m*n)
8+
Space : O(m*n)
9+
*/
10+
11+
class Solution {
12+
public:
13+
int maximalSquare(vector<vector<char>>& matrix) {
14+
int rows = matrix.size(), cols = matrix[0].size();
15+
16+
vector<vector<int>> dp (rows+1, vector<int>(cols+1, 0));
17+
int maxi = 0;
18+
for(int i = rows-1 ; i >= 0; --i) {
19+
for(int j = cols-1 ; j >=0 ; --j) {
20+
if(matrix[i][j] == '1') {
21+
int right = dp[i][j+1], dia = dp[i+1][j+1], bottom = dp[i+1][j];
22+
23+
dp[i][j] = 1 + min(right, min(dia, bottom));
24+
maxi = max(maxi, dp[i][j]);
25+
}
26+
else {
27+
dp[i][j] = 0;
28+
}
29+
}
30+
}
31+
return maxi*maxi;
32+
}
33+
};

0 commit comments

Comments
 (0)