Largest submatrix with equal no of 1's and 0's

后端 未结 4 1954
抹茶落季
抹茶落季 2020-12-24 09:41

Given a matrix of size mxn containing 0\'s and 1\'s only. I need to find the largest sub-matrix which has equal number of 1\'s and 0\'s in it. Brute force appro

4条回答
  •  渐次进展
    2020-12-24 10:23

    This algorithm assumes that we search a sub-matrix with contiguous rows and columns and with the largest possible product of height and width.

    Start with the following pre-processing:

    A = substitute_zero_with_minus_one(InputMatrix)
    B = prefix_sum_for_each_column(A)
    C = prefix_sum_for_each_row(B)
    

    Now for each pair of rows (i, j) do the folowing:

    for each column k:
      d = C[k, j] - C[k, i]
      if h[d] not empty:
        if (k - h[d]) * (j - i) is greater than best result:
          update best result
      else:
        h[d] = k
    

    Time complexity is O(N2 * M), extra space is O(N * M).

提交回复
热议问题