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

Maximal Rectangle

时间:2014-06-11 00:24:51      阅读:343      评论:0      收藏:0      [点我收藏+]

标签:leetcode   数组   java   

题目

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

方法

使用两个矩阵,分别记录每一行连续的1的个数以及每一列连续的1的个数。
    public int maximalRectangle(char[][] matrix) {
        int lenX = matrix.length;
        if (lenX == 0) {
            return 0;
        }
        int lenY = matrix[0].length;
        int[][] maxRec = new int[lenX][lenY];
        int[][] height = new int[lenX][lenY];
        int[][] length = new int[lenX][lenY];
        for (int i = 0; i < lenX; i++) {
        	for (int j = 0; j < lenY; j++) {
        		if (matrix[i][j] == '1') {
        			if (j == 0) {
        				length[i][j] = 1;
        			} else {
        				length[i][j] = length[i][j - 1] + 1;
        			}
        			
        			if (i == 0) {
        				height[i][j] = 1;
        			} else {
        				height[i][j] = height[i - 1][j] + 1;
        			}
        		} else {
        			length[i][j] = 0;
        			height[i][j] = 0;
        		}
        	}
        }
        
        for (int i = 0; i < lenX; i++) {
            for (int j = 0; j < lenY; j++) {
            	int h = height[i][j];
            	int l = length[i][j];
            	int minHeight = h;
            	int max = 0;
            	for (int k = 1; k <= l; k++) {
            		minHeight = Math.min(minHeight, height[i][j + 1 - k]);
            		max = Math.max(max, k * minHeight);
            	}
            	maxRec[i][j] = max;
            }
        }
        int max = 0;
        for (int i = 0; i < lenX; i++) {
            for (int j = 0; j < lenY; j++) {
                if (maxRec[i][j] > max) {
                    max = maxRec[i][j];
                }
            }
        }
        return max;
    }


Maximal Rectangle,布布扣,bubuko.com

Maximal Rectangle

标签:leetcode   数组   java   

原文地址:http://blog.csdn.net/u010378705/article/details/29360077

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