首页 > 其他 > 详细

85. Maximal Rectangle

时间:2021-01-19 12:25:57      阅读:25      评论:0      收藏:0      [点我收藏+]
package LeetCode_85

/**
 * 85. Maximal Rectangle
 * https://leetcode.com/problems/maximal-rectangle/
 * Given a rows x cols binary matrix filled with 0‘s and 1‘s,find the largest rectangle containing only 1‘s and return its area.
Example 1:
Input: matrix =[
["1","0","1","0","0"],
["1","0","1","1","1"],
["1","1","1","1","1"],
["1","0","0","1","0"]]
Output: 6
Explanation: The maximal rectangle is shown in the above picture.

Example 2:
Input: matrix = []
Output: 0

Example 3:
Input: matrix = [["0"]]
Output: 0

Example 4:
Input: matrix = [["1"]]
Output: 1

Example 5:
Input: matrix = [["0","0"]]
Output: 0

Constraints:
1. rows == matrix.length
2. cols == matrix.length
3. 0 <= row, cols <= 200
4. matrix[i][j] is ‘0‘ or ‘1‘.
 * */
class Solution {
    /*
    * solution: DP, update height of each columns,
    * Time:O(m*n*m), Space:O(mn)
    * */
    fun maximalRectangle(matrix: Array<CharArray>): Int {
        var result = 0
        val m = matrix.size
        if (m == 0) {
            return 0
        }
        val n = matrix[0].size
        //dp[i][j]: max length of all 1s end with col[j] at row[i]
        val dp = Array(m) { IntArray(n) }
        for (i in matrix.indices) {
            for (j in matrix[i].indices) {
                //set up height array
                dp[i][j] = if (matrix[i][j] == ‘1‘) {
                    if (j == 0) {
                        1
                    } else {
                        dp[i][j - 1] + 1
                    }
                } else {
                    0
                }
            }
        }
        /*
        for example matrix =
        ["1","0","1","0","0"],
        ["1","0","1","1","1"],
        ["1","1","1","1","1"],
        ["1","0","0","1","0"]]
        heights array:
         1,0,1,0,0,
         1,0,1,2,3,
         1,2,3,4,5,
         1,0,0,1,0,
        * */
        for (i in 0 until m) {
            for (j in 0 until n) {
                var height = Int.MAX_VALUE
                //scan current row, find out minimum value
                for (k in i until m) {
                    height = Math.min(height, dp[k][j])
                    //area = height * width
                    result = Math.max(result, height * (k - i + 1))
                }
            }
        }
        return result
    }
}

 

85. Maximal Rectangle

原文:https://www.cnblogs.com/johnnyzhao/p/14297175.html

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