forked from lennylxx/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
221.cpp
72 lines (57 loc) · 1.99 KB
/
221.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include <iostream>
#include <algorithm>
#include <vector>
#include <cassert>
using namespace std;
class Solution {
public:
int maximalSquare(vector<vector<char>>& matrix) {
int rows = matrix.size();
if (rows == 0) return 0;
int cols = matrix[0].size();
vector<vector<int> > dp(rows, vector<int>(cols));
int i, j;
int max_edge = 0;
for (j = 0; j < cols; j++) {
dp[0][j] = (matrix[0][j] == '1') ? 1 : 0;
max_edge = max(dp[0][j], max_edge);
}
for (i = 0; i < rows; i++) {
dp[i][0] = (matrix[i][0] == '1') ? 1 : 0;
max_edge = max(dp[i][0], max_edge);
}
for (i = 1; i < rows; i++) {
for (j = 1; j < cols; j++) {
if (matrix[i][j] != '1') {
dp[i][j] = 0;
}
else {
dp[i][j] = 1;
if (matrix[i - 1][j - 1] == '1' &&
matrix[i - 1][j] == '1' &&
matrix[i][j - 1] == '1') {
dp[i][j] += min(dp[i - 1][j - 1],
min(dp[i - 1][j], dp[i][j - 1]));
}
max_edge = max(dp[i][j], max_edge);
}
}
}
return max_edge * max_edge;
}
};
int main() {
vector<vector<char> > matrix1{{'1', '0', '1', '0', '0'},
{'1', '0', '1', '1', '1'},
{'1', '1', '1', '1', '1'},
{'1', '0', '0', '1', '1'}};
vector<vector<char> > matrix2{{'1', '0', '1', '0', '0'},
{'1', '0', '1', '1', '1'},
{'1', '1', '1', '1', '1'},
{'1', '0', '1', '1', '1'}};
Solution s;
assert(s.maximalSquare(matrix1) == 4);
assert(s.maximalSquare(matrix2) == 9);
printf("all tests passed!\n");
return 0;
}