Megha Singh
Megha Singh

Reputation: 51

How can we print all sub matrices of a given 2D matrix in Java?

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.

Upvotes: 2

Views: 2543

Answers (2)

Satyendra Ranjan
Satyendra Ranjan

Reputation: 11

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];

Upvotes: 1

Assafs
Assafs

Reputation: 3275

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);
  }

Upvotes: 3

Related Questions