算法课作业系列12
Maximal Rectangle
题目
Given a 2D binary matrix filled with 0’s and 1’s, find the largest rectangle containing only 1’s and return its area.
For example, given the following matrix:
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
Return 6.
思路
这道题我想了很久,但是都一一推翻,一个小时之后,我去了讨论区……
言归正传,这道题的思路我是真的想不到的,我根据题目的特征,也就是长方体,想找对角线来决定,然而都失败了,这里只是列举出我学习到的算法,并不是我自己想到的。
1. 找到左边界和右边界
2. 找到高
我来解释一下,意思就是对于每个位置,找到每一行的左边界和右边界,从而决定有多宽,具体数值根据当前行和上一行的清苦昂决定;那决定高就很好理解了,看看纵向能延展多少,从而根据底和高确定出最后面积
参考代码
class Solution {
public:
int maximalRectangle(vector<vector<char>>& matrix) {
vector<vector<int> > left(matrix.size());
vector<vector<int> > right(matrix.size());
vector<vector<int> > height(matrix.size());
int max = 0;
for (int i = 0; i < matrix.size(); i++) {
vector<int> tmp(matrix[0].size());
left[i] = tmp;
right[i] = tmp;
height[i] = tmp;
for (int j = 0; j < matrix[0].size(); j++) {
if (matrix[i][j] == '0') {
left[i][j] = 0;
right[i][j] = matrix[0].size();
height[i][j] = 0;
} else {
int k, l;
for (k = j - 1; k >= 0; k--) {
if (matrix[i][k] == '0') {
break;
}
}
k += 1;
for (l = j + 1; l < matrix[0].size(); l++) {
if (matrix[i][l] == '0') {
break;
}
}
if (i == 0) {
left[i][j] = k;
right[i][j] = l;
height[i][j] = 1;
} else {
left[i][j] = k > left[i - 1][j]?k:left[i - 1][j];
right[i][j] = l < right[i - 1][j]?l:right[i - 1][j];
height[i][j] = height[i - 1][j] + 1;
}
}
int ret = (right[i][j] - left[i][j]) * height[i][j];
if (ret > max) {
max = ret;
}
}
}
return max;
}
};