首页 > 其他 > 详细

Maximal Rectangle

时间:2014-06-11 00:24:31      阅读:514      评论: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.

方法

使用两个矩阵,分别记录每一行连续的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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!