Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can we generate all submatrix of a given 2D matrix in java or C++?

I am using this loop structure but it fails to generate all the submatrix that are possible for any given 2D matrix with n rows and m columns.

  for(i=0;i<n;i++)
    {
        for(j=0;j<m;j++)
        {
            System.out.println("sub-MATRIX:");
            for(k=i;k<n;k++)
            {
                for(p=j;p<m;p++)
                {
                   System.out.print(arr[k][p]+" ");
                }
                System.out.println();
            }
        }
    }

Ex: Given matrix 3X3 : [[1 2 3],[4 5 6],[7 8 9]] Then its submatrix will be: for size 1: [1],[2],[3],[4],[5],[6],[7],[8],[9] for size 4: [[1,2],[4,5]],[[2,3],[5,6]],[[4,5],[7,8]] and [[5,6],[8,9]] and so on

like image 652
mohdanishh Avatar asked Oct 18 '25 14:10

mohdanishh


2 Answers

You are missing a couple more loops to cover all cases. PrintMatyrix() should have 2 nested loops for printing contents.

  for (i = 1; i < n; ++i)
  {
    for (j = 1; j < m; ++j)
    {
      // we are at each sub matrix of size(i,j)
      for (k = 0; k <= (n - i); ++k)
      {
        for (p = 0; p <= (m - j); ++p)
        {
           // we are at submatrix of size(i,j) starting at (k,p)
           // assuming PrintMatrix(Matrix&, int rows, int cols, int r0, int c0);   
           PrintMatrix(arr, i, j, k, p);
        }
      }
    }
  }
like image 77
Michaël Roy Avatar answered Oct 21 '25 04:10

Michaël Roy


If we have a matrix with dimensions M x N, and the sub matrix we are looking for is with K x L dimensions. If there is more optimized solution, please share.

for (int i = 0; i < m-k+1; i++) {   
                for (int j = 0; j < n-l+1; j++) {
                    for (int p = 0; p < k; p++) {
                        for(int q = 0; q < l; q++) {
                            System.out.print(arr[i+p][j+q] + " ");
                        }
                        System.out.println();
                    }
                    System.out.println("*****************");

                }
            }
like image 27
Frosina Andonovska Avatar answered Oct 21 '25 02:10

Frosina Andonovska