Skip to content

Commit 97d5f20

Browse files
committed
矩阵里面的DP思想,设定相关变量记录有用信息
1 parent 42a9165 commit 97d5f20

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

DP-DFS-memo/Maximal Rectangle

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
// 说是DP,但是没有严格的状态转移方程,是通过‘0’和‘1’去设定的变量值,每一个元素对应的相关几个变量的设置,然后再通过
2+
这几个变量得到area ,并记录求最大值
3+
class Solution {
4+
public:
5+
int maximalRectangle(vector<vector<char> > &matrix) {
6+
int n = matrix.size();
7+
int area = 0;
8+
if(n == 0 )
9+
return 0;
10+
int m = matrix[0].size();
11+
vector<int> H(m,0);
12+
vector<int> L(m,0);
13+
vector<int> R(m,m); // record the info,use this info to realize DP
14+
15+
for(int i = 0;i < n;i++)
16+
{
17+
int left = 0,right = m; // 每一行比较的两个变量
18+
for(int j = 0;j < m;j++)
19+
{
20+
if(matrix[i][j] == '1')
21+
{
22+
++H[j]; // 对应的位置上有多少有效行
23+
L[j] = max(L[j],left); //该位置上最左边1的位置
24+
}
25+
else
26+
{
27+
left = j+1;// 与下面的right = j 对应,求得正确的距离
28+
H[j] = 0; // 若不是1对应的位置相关的记录都是初值
29+
L[j] = 0;
30+
R[j] = m;
31+
}
32+
}
33+
for( int j = m-1;j >= 0;--j)//确定最右边的值,所以从后面开始遍历
34+
{
35+
if (matrix[i][j] == '1')
36+
{
37+
R[j]=min(R[j],right);// 确定该位置最右边为1的位置
38+
area = max(area,H[j] * (R[j] - L[j])); // 累积比较
39+
}
40+
else
41+
right = j; // 这里是j 求距离的!
42+
43+
}
44+
45+
}
46+
return area;
47+
}
48+
};

0 commit comments

Comments
 (0)