I want find the biggest submatrix which contains only negative numbers in a matrix, for example:
In
[[1, -9, -2, 8, 6, 1],
[8, -1,-11, -7, 6, 4],
[10, 12, -1, -9, -12, 14],
[8, 10, -3, -5, 17, 8],
[6, 4, 10, -13, -16, 19]]
the biggest submatrix containing only negative numbers is
[[-11, -7],
[-1, -9],
[-3,-5]]
(left upper corner coordinates: 1,2, right lower corner coordinates: 3,3).
What's the most effective way to do it?
A brute force solution. Will work, but may be considered too slow for a bigger matrix:
Will output
In case something else is meant with "biggest submatrix", the only function that needs to get changed is the following:
which is calculating the size of a submatrix.
Edit 1 ... first speedup
Edit 2
Ok, after converting the matrix into a matrix of 0 and 1 (as I do via the line
m = [[1 if x < 0 else 0 for x in z] for z in mOrig]
the problem is the same as what is calledthe maximal rectangle problem
in literature. So I googled a bit about known algorithms for this kind of problem and came across this site here http://www.drdobbs.com/database/the-maximal-rectangle-problem/184410529 which is describing a very fast algorithm to solve this kind of problem. To summarize the points of this website, the algorithm is exploiting the structure. This can be done by using a stack in order to remember the structure profile which allows us to recalculate the width in case a narrow rectangle gets reused when an wider one gets closed.