Reputation: 461
This is a question asked in one job interview. I would like to know the best optimal algorithm for getting desired results. The question is : Given you have a (n x m) matrix with some numbers in it. Now you have to count the no of matrices of size >= (2 x 2) which will have following two conditions :
I know the brute force algorithm of taking all elements of matrix 2 x 2 and greater; then counting the no. of 1's and checking 6 possible conditions of corner elements any two of them being equal. I want to know the way of dealing with these problems or any source as I could not found anything on "GeeksForGeeks" or StackOverFlow itself , in most optimized way.
Upvotes: 3
Views: 307
Reputation: 148910
This is a hint to an optimized way.
First build a (n,m) matrix that counts the number of 1
in the (1-i, 1-j) submatrix: nm operations, nm memory
Now for each element of the matrix, search for all elements after of below that are equal
The above is only the rough edges and there is still some work to design an algorythm, but it should be a little better than brute force for big enough matrices...
Upvotes: 3