Find largest rectangle containing only zeros in an N×N binary matrix

前端 未结 8 2193
伪装坚强ぢ
伪装坚强ぢ 2020-11-22 06:25

Given an NxN binary matrix (containing only 0\'s or 1\'s), how can we go about finding largest rectangle containing all 0\'s?

Example:

      I
    0          


        
8条回答
  •  情深已故
    2020-11-22 06:35

    I propose a O(nxn) method.

    First, you can list all the maximum empty rectangles. Empty means that it covers only 0s. A maximum empty rectangle is such that it cannot be extended in a direction without covering (at least) one 1.

    A paper presenting a O(nxn) algorithm to create such a list can be found at www.ulg.ac.be/telecom/rectangles as well as source code (not optimized). There is no need to store the list, it is sufficient to call a callback function each time a rectangle is found by the algorithm, and to store only the largest one (or choose another criterion if you want).

    Note that a proof exists (see the paper) that the number of largest empty rectangles is bounded by the number of pixels of the image (nxn in this case).

    Therefore, selecting the optimal rectangle can be done in O(nxn), and the overall method is also O(nxn).

    In practice, this method is very fast, and is used for realtime video stream analysis.

提交回复
热议问题