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

后端 未结 4 1942
抹茶落季
抹茶落季 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:42

    I assume a submatrice is formed using only contiguous rows\columns of the original matrix (ie by removing first\last row or columns).

    This way, a matrix can be represented as

    Mat = {origin(row,col), rowCount, columnCount}
    

    If the original matrix is of dimension M x N, then

    rowCount =  M - row
    columnCount = N - col
    Mat = {origin(row,col), M - row, N - col}.
    

    The variable row and col has respectively M and N possible values, which means there are O(MxN) of such matrices.

    Idea of Algorithm

    1. pop matrix (m, n)from queue
    2. Test . If success, output matrix
    3. Construct all matrices (m, n-1) and (m-1, n) and put on queue
    4. go back to 1.

    Now there are two points:

    • When you reduce dimensions there are only 4 possible matrices (2 by removing rows, 2 by removing columns)
    • You construct a sub matrix by remove either the first and last row\column. You just need remove the count for the row\column you removed, which takes O(n) or O(m) time. this is the dynamic programming step.

    Which mean the complexity is O(max(M,N)MN)

提交回复
热议问题