2

Suppose I have a matrix of size, say 5*6. I need all the sub matrices, that is, of size 1*1, 1*2, 2*5,3*2,5*4 etc. How do I obtain it?

for (i = 0; i < n; i++) {
 for (j = 0; j < m; j++) {
  int arr[][] = new int[i + 1][j + 1];
  for (x = 0; x < i + 1; x++) {
   for (y = 0; y < j + 1; y++) {
    arr[x][y] = a[x][y];
    System.out.print(arr[x][y] + "  ");
   }
   System.out.println();
  }
  System.out.println("*********next********");
 }
}

This is my code till now. But this is printing the subarray of desired sizes only starting from 0,0 index.

10 Replies
  • 426
  • 9
  • 25

2 Answers2

3

You can try this code:

public static void printMatrix (int columnStart, int rowStart, int columnSize, int rowSize, int[][] matrix) {
    if (columnStart+columnSize>matrix[0].length) return;
    if (rowStart+rowSize>matrix.length) return;
    for (int i=rowStart;i<rowStart+rowSize;i++) {
      for (int j=columnStart;j<columnStart+columnSize;j++) {
        System.out.print(matrix[i][j]+" ");
      }
      System.out.println();
    }
    System.out.println("*********next********");
  }

  public static void printAllSubMatrices (int[][] matrix) {
    for (int i=0;i<matrix.length;i++) {
      for (int m=1;m<matrix.length-i+1;m++) {
        for (int j=0;j<matrix[0].length;j++) {
          for (int n=1;n<matrix[0].length-j+1;n++) {
            printMatrix(j, i, n, m, matrix);
          }
        }
      }
    }
  }
  public static void main(String[] args) {
    int[][] matrix = {{1,2,3},{4,5,6},{7,8,9}};
    //This will print you all the 36 sub-matrices of 3X3 matrix
    printAllSubMatrices(matrix);
  }
Assafs
  • 3,257
  • 4
  • 26
  • 39
  • But this code is not working for non-square matrices. How should we code it for M*N matrix? – Megha Singh Aug 06 '17 at 20:23
  • I can look at it tomorrow to confirm - but I think it should work for any n*m matrix. I gave the 3x3 matrix in the main of the code as an example only. You should be able to get correct results with 3x4 matrix. If you notice an issue tell me what you see - and I'll offer a fix. – Assafs Aug 06 '17 at 20:29
  • I tried it for a 2*3 matrix = {{1,2,3},{4,5,6}}. But it didn't display all submatrices. – Megha Singh Aug 06 '17 at 20:34
  • Ok. I'll look again tomorrow morning. – Assafs Aug 06 '17 at 20:35
  • Fixed - it was a typo in the line for (int n=1;n – Assafs Aug 07 '17 at 06:19
1

This is a problem of O(n^6) Brute force .

int a[][]= new int [m][n];
for(int i =0 ; i<m;i++)
for(int j=0;j<n;j++)
for(int r=i;i<m;i++)
for(int c=j;c<n;c++)
for(int l1=i ;l1<r;l1++)
for(int l2=j; l2<c;l2++)
 print a[l1][l2];