Maximal Rectangle

Maximal Rectangle 題解


題目描述

Maximal Rectangle
即尋找矩陣S中最大的被1填充的矩形子塊面積。矩形子塊s面積即字面義:矩形子塊s的面積。
如:S=segmentfault

[1 0 1 0 0
 1 0 1 1 1
 1 1 1 1 1
 1 0 0 1 0]

最大的矩形子塊面積6,此矩形子塊s=[1 1 1; 1 1 1]ui

題解

Largest Rectangle in Histogram的變形。能夠這麼轉換,二維的矩形的橫軸對應Histogram的長度,縱軸對應Histogram的高度。從左到右,從上到下遍歷一次便可。假設矩陣大小爲n * n,時間複雜度爲O(n^2),空間複雜度爲O(n)spa

代碼

typedef unsigned int uint;
static const uint MAX_SIZE = 0x100;
static uint keep[MAX_SIZE], heights[MAX_SIZE];
class Solution {
public:
    int maximalRectangle(vector<vector<char>>& matrix) {
        size_t rect = 0U;
        memset(heights, 0, sizeof(heights));
        for (size_t i = matrix.size(); i--; ) {
            const vector<char>& vec = matrix[i];
            size_t len = vec.size(), keepEnd = 0;
            for (keep[0] = len; len--; keep[++keepEnd] = len) {
                heights[len] = vec[len] == '0'? 0 : heights[len] + 1;
                uint tmp = heights[len], pos = keep[keepEnd];
                do {
                    uint area = heights[pos];
                    if (tmp >= area)
                        break;
                    pos = keep[--keepEnd];
                    if ((area *= (pos - len - 1U)) > rect)
                        rect = area;
                } while (keepEnd);
            }

            while (keepEnd) {
                uint area = heights[keep[keepEnd]];
                if ((area *= keep[--keepEnd]) > rect)
                    rect = area;
            }
        }
        return rect;
    }
};

總結

主要應用了等價轉化的思想。code

相關文章
相關標籤/搜索