1. 程式人生 > 其它 >leetcode221.最大正方形

leetcode221.最大正方形

leetcode221.最大正方形

題目

在一個由 '0''1' 組成的二維矩陣內,找到只包含 '1' 的最大正方形,並返回其面積。

用例

輸入:matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
輸出:4
輸入:matrix = [["0","1"],["1","0"]]
輸出:1
輸入:matrix = [["0"]]
輸出:0

求解

/**
 * @param {character[][]} matrix
 * @return {number}
 */
var maximalSquare = function(matrix) {
    let res = 0
    for(let i=0;i<matrix.length;i++){
        let heights=[]
        for(let j=0;j<matrix[0].length;j++){
            let height=0
            let tmp_i = i
            while(tmp_i>=0&&matrix[tmp_i][j]==1){
                height++
                tmp_i--
            }
            heights.push(height)
        }
        find_max(heights)
    }
    return res

    function find_max(heights){
        for(let i=0;i<heights.length;i++){
            //以第i個高度為起點所能形成的最大矩陣
            let min_height=heights[i]
            let width = 1
            let j=i
            while(j<heights.length&&width<=min_height){
                max_square = width*width
                if(max_square>res){
                    res=max_square
                }
                j++
                width++
                if(heights[j]<min_height){
                    min_height=heights[j]
                }
            }
        }
    }
};