package com.app.main.LeetCode.dynamic;
/**
* 85
*
* hard
*
* https://leetcode.com/problems/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.
*
* Example:
*
* Input:
* [
* ["1","0","1","0","0"],
* ["1","0","1","1","1"],
* ["1","1","1","1","1"],
* ["1","0","0","1","0"]
* ]
* Output: 6
*
*
* Created with IDEA
* author:Dingsheng Huang
* Date:2019/12/18
* Time:下午3:20
*/
public class MaximalRectangle {
int max = 0;
int[][] matrix2;
public int maximalRectangle(char[][] matrix) {
int x = matrix[0].length;
int y = matrix.length;
matrix2 = new int[y][x];
for (int i = 0; i < x; i++) {
matrix2[0][i] = matrix[0][i] == '1' ? 1 : 0;
for (int j = 1; j < y; j++) {
matrix2[j][i] = matrix[j][i] == '1' ? matrix2[j - 1][i] + 1 : matrix2[j - 1][i];
}
}
// divide y
for (int i = 1; i <= y; i++) {
process(matrix, i);
}
return max;
}
private void process(char[][] matrix, int y) {
for (int i = 0; i < matrix.length; i++) {
if (i + y <= matrix.length) {
help(matrix, i, i + y - 1);
}
}
}
private void help(char[][] matrix, int y1, int y2) {
int pre = 0;
int currMax = 0;
for (int i = 0; i < matrix[0].length; i++) {
if (y1 == 0) {
if ((matrix2[y2][i]) == (y2 - y1 + 1)) {
currMax = Math.max(currMax, pre + 1);
pre++;
} else {
pre = 0;
}
} else {
if ((matrix2[y2][i] - matrix2[y1 - 1][i]) == (y2 - y1 + 1)) {
currMax = Math.max(currMax, pre + 1);
pre++;
} else {
pre = 0;
}
}
}
max = Math.max(currMax * (y2 - y1 + 1), max);
}
}
LeetCode--85--hard--MaximalRectangle
猜你喜欢
转载自blog.csdn.net/huangdingsheng/article/details/103809837
今日推荐
周排行