Skip to content

Commit d129a6b

Browse files
Add files via upload
1 parent cff32cb commit d129a6b

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

Maximal Square/Maximal_Square.cpp

+61
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
// 动态规划
2+
3+
// Runtime: 16 ms, faster than 97.02% of C++ online submissions for Maximal Square.
4+
// Memory Usage: 10.6 MB, less than 86.19% of C++ online submissions for Maximal Square.
5+
6+
class Solution
7+
{
8+
public:
9+
int maximalSquare(vector<vector<char>>& matrix)
10+
{
11+
// 边界条件处理
12+
int rows = matrix.size();
13+
if (rows == 0) return 0;
14+
15+
int cols = matrix[0].size();
16+
if (cols == 0) return 0;
17+
18+
int maxArea = 0;
19+
vector<int> left(cols, -1);
20+
vector<int> right(cols, cols);
21+
vector<int> height(cols, 0);
22+
23+
for (int i = 0; i < rows; ++i)
24+
{
25+
int curLeft = 0, curRight = cols - 1;
26+
27+
for (int j = 0; j < cols; ++j)
28+
{
29+
if (matrix[i][j] == '1')
30+
{
31+
left[j] = max(left[j], curLeft);
32+
++height[j];
33+
}
34+
else
35+
{
36+
height[j] = 0;
37+
curLeft = j + 1;
38+
left[j] = -1;
39+
}
40+
}
41+
42+
for (int j = cols - 1; j >= 0; --j)
43+
{
44+
if (matrix[i][j] == '1')
45+
{
46+
right[j] = min(right[j], curRight);
47+
48+
int h = height[j];
49+
int w = right[j] - left[j] + 1;
50+
maxArea = max(maxArea, min(w, h) * min(w, h));
51+
}
52+
else
53+
{
54+
curRight = j - 1;
55+
right[j] = cols;
56+
}
57+
}
58+
}
59+
return maxArea;
60+
}
61+
};

0 commit comments

Comments
 (0)