-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmaximal_square.cpp
More file actions
67 lines (62 loc) · 1.76 KB
/
maximal_square.cpp
File metadata and controls
67 lines (62 loc) · 1.76 KB
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
/*
* =====================================================================================
*
* Filename: maximal_square.cpp
*
* Description: 221. Maximal Square
*
* Version: 1.0
* Created: 12/20/2025 17:49:26
* Revision: none
* Compiler: gcc
*
* Author: Michael Zhu, xianfeng.zhu@gmail.com
* Organization:
*
* =====================================================================================
*/
#include <utility>
#include <vector>
#include "gtest/gtest.h"
class Solution {
public:
int maximalSquare(std::vector<std::vector<char>>& matrix) {
const int m = matrix.size();
const int n = matrix[0].size();
std::vector<std::vector<int>> dp(m, std::vector<int>(n));
int res = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] == '0') {
continue;
}
int left = (j > 0) ? dp[i][j - 1] : 0;
int up = (i > 0) ? dp[i - 1][j] : 0;
int diagonal = (i > 0 && j > 0) ? dp[i - 1][j - 1] : 0;
dp[i][j] = std::min({left, up, diagonal}) + 1;
res = std::max(res, dp[i][j]);
}
}
return res * res;
}
};
TEST(Solution, maximalSquare) {
std::vector<std::pair<std::vector<std::vector<char>>, int>> cases = {
{{{'1', '0', '1', '0', '0'},
{'1', '0', '1', '1', '1'},
{'1', '1', '1', '1', '1'},
{'1', '0', '0', '1', '0'}},
4},
{{{'0', '1'}, {'1', '0'}}, 1},
{{{'0'}}, 0},
{{{'1', '1', '1', '1', '0'},
{'1', '1', '1', '1', '0'},
{'1', '1', '1', '1', '1'},
{'1', '1', '1', '1', '1'},
{'0', '0', '1', '1', '1'}},
16},
};
for (auto& [matrix, res] : cases) {
EXPECT_EQ(Solution().maximalSquare(matrix), res);
}
}