Best/Fastest way to iterate through all sub-matrices of a NxN matrix

Go To StackoverFlow.com

0

I have a square board (NxN matrix). Each square (cell) has a certain points associated to it. My goal is to find the largest sub-matrix which has the highest summation of points. I started off with trying to find all the sub-matrices and their weights. But I am stuck on how to go about doing it.

I thought I could have a HashMap<String,Integer> which stores the initial row,column and the size of the sub matrix. The code should look something like this:

int [][] mat = new int[10][10];

void countSubMatrix()
{
    for(int i = 0; i<mat.length; i++)
    {
        for(int j = 0; j<mat[i].length; j++)
        {
            storeSubMatrix(i,j);
        }
    }
}

void storeSubMatrix(int x, int y)
{
    int size = 0;
    int tempX = x;
    int tempY = y;
    while(tempX < board.length && tempY < board[x].length)
    {
        map.put(x.toString() + "," + y.toString(),size+1);
        tempX++;
        tempY++;
    }
}

But I don't know if this is the right way to do it. Any thoughts?

2012-04-04 22:53
by noMAD
Do the sub-matrices have to be square too? Can they be any size less than NxN? Can the cell values be negative - DNA 2012-04-04 22:58
They have to be square too. And yes, any size less than NxN. Well, in my game there are no negative values but that is a good question though. How would it matter if a cell has negative value - noMAD 2012-04-04 23:06
@noMAD: If there are no negative values, the answer is trivial - the complete matrix [which is by definition also a submatrix of itself] has no less summation then any of its submatrixes - thus it is maximal. However - I doubt that this is what you are really after.. - amit 2012-04-04 23:19
Finding all the submatrices sounds like a job for recursion. But as the others have said its probably not going to get you what you're after in the bigger picture - davidfrancis 2012-04-04 23:26
@amit: That's true. I was being silly. I need to change stuff in my design. Anyways, I will be having negative numbers in the matrix - noMAD 2012-04-05 00:13


0

Largest submatrix ,i.e, it can also be a rectangle, then this might be of help to you. Using kadane's algorithm for matrix it can be done in O(n^3).

2012-04-05 00:55
by Priyank Bhatnagar
Can you elaborate on the O(n^2) solution - noMAD 2012-04-05 03:51
@noMAD, sorry I confused this with some other problem. I don't think it is possible in less than O(n^3) - Priyank Bhatnagar 2012-04-05 04:31
Alright, I would like to know how it can be done in O(n^3)??? How will you apply Kadane's algorithm here - noMAD 2012-04-05 05:21
@noMAD, read the link, it is explained there - Priyank Bhatnagar 2012-04-05 06:56
Ads