码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode - Maximal Rectangle

时间:2016-01-03 18:20:50      阅读:110      评论:0      收藏:0      [点我收藏+]

标签:

题目:

Given a 2D binary matrix filled with 0‘s and 1‘s, find the largest rectangle containing all ones and return its area.

思路:

类似于上一篇文章中的方法一,对每列的左右拓展极限进行记录,同时保存当前列的高度。

package area;

public class MaximalRectangle {

    public int maximalRectangle(char[][] matrix) {
        int m;
        int n;
        if (matrix == null || (m = matrix.length) == 0 || (n = matrix[0].length) == 0) return 0;
// Height of this column
int[] H = new int[n]; int[] L = new int[n]; int[] R = new int[n]; for (int i = 0; i < n; ++i) { H[i] = 0; L[i] = 0; R[i] = n; } int max = 0; for (int i = 0; i < m; ++i) { int left = 0; int right = n; for (int j = 0; j < n; ++j) { if (matrix[i][j] == ‘1‘) { ++H[j]; L[j] = Math.max(L[j], left); } else { left = j + 1; H[j] = 0; L[j] = 0; R[j] = n; } } for (int j = n - 1; j >= 0; --j) { if (matrix[i][j] == ‘1‘) { R[j] = Math.min(R[j], right); max = Math.max((R[j] - L[j]) * H[j], max); } else { right = j; } } } return max; } public static void main(String[] args) { // TODO Auto-generated method stub char[][] matrix = { { ‘0‘, ‘1‘, ‘1‘, ‘0‘, ‘1‘ }, { ‘1‘, ‘1‘, ‘0‘, ‘1‘, ‘0‘ }, { ‘0‘, ‘1‘, ‘1‘, ‘1‘, ‘0‘ }, { ‘1‘, ‘1‘, ‘1‘, ‘1‘, ‘0‘ }, { ‘1‘, ‘1‘, ‘1‘, ‘1‘, ‘1‘ }, { ‘0‘, ‘0‘, ‘0‘, ‘0‘, ‘0‘ } }; MaximalRectangle m = new MaximalRectangle(); System.out.println(m.maximalRectangle(matrix)); } }

 

LeetCode - Maximal Rectangle

标签:

原文地址:http://www.cnblogs.com/shuaiwhu/p/5096766.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!