Compute cumulative sum of rows R[i,j] and columns C[i,j].
For top-left corner (i,j) of each possible sub-rectangle:
Starting from a single-row sub-rectangle (n=i),
Search the last possible column for this sub-rectangle (m).
While m>=j:
While there are more than 'k' "ones" in this sub-rectangle:
If this is the smallest sub-rectangle so far, remember it.
Remove column (--m).
This decreases the number of "ones" by C[m+1,n]-C[m+1,j-1].
Add next row (++n).
This increases the number of "ones" by R[m,n]-R[i-1,n].
時間計算量は O(NM(N+M)) です。
ネストされた 2 つのループは、線形検索を二分検索に変更することで最適化できます (細いサブ長方形をより高速に処理するため)。
また、(行/列をサブ長方形に追加した後)、このサブ長方形の面積が面積より大きくならないように、列/行の数を O(1) 倍に減らすこともできます。これまでで最高のサブ長方形の。
これらの最適化は両方とも、O(1) のサブ長方形の重みの計算を必要とします。それを可能にするために、サブ長方形 [1..i,1..j] (X[i,j]) のすべての要素の累積合計を事前に計算します。次に、サブ長方形 [i..m,j..n] の重みは として計算されX[m,n]-X[i-1,n]-X[m,j-1]+X[i-1,j-1]
ます。
Compute cumulative sum of columns C[i,j].
For any starting row (k) of possible sub-rectangle:
For any ending row (l) of possible sub-rectangle:
Starting column (m = 1).
Ending column (n = 1).
While n is not out-of-bounds
While there are less than 'k' "ones" in sub-rectangle [k..l,m..n]:
Add column (++n).
This increases the number of "ones" by C[l,n]-C[k-1,n].
If this is the smallest sub-rectangle so far, remember it.
Remove column (++m).
This decreases the number of "ones" by C[l,m-1]-C[k-1,m-1].
時間計算量は O(N 2 M) です。
'l' によるループは、内部で処理されたすべてのサブ長方形が単一列のサブ長方形である (行が多すぎる) 場合、または内部で処理されたサブ長方形に十分な「1」が含まれていない (行が不足している) 場合に終了する可能性があります。 )。