Skip to content

Instantly share code, notes, and snippets.

@AseedUsmani
Last active June 10, 2018 10:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AseedUsmani/11554e4799b8019ef49c06ca42900323 to your computer and use it in GitHub Desktop.
Save AseedUsmani/11554e4799b8019ef49c06ca42900323 to your computer and use it in GitHub Desktop.
/* QUESTION
Given a matrix, find largest submatrix where the sum of its elements is zero, and print its size
*/
// First take input...
/* Example in Java using Scanner class, you can use C if you are comfortable with it*/
Scanner sc=new Scanner(System.in); //make sure you have imported Scanner class using `import java.util.Scanner;`
int m = sc.nextInt();
int n = sc.nextInt();
int matrix=new int[m][n];
for(int i=0; i<m; i++) {
for(int j=0; j<n; j++) matrix[i][j]=sc.nextInt();
}
//now input is done, use brute force to find largest sub-matrix
int size=0; //to store current size
int max=0; //to store max
for(int i=0; i<m; i++) {
for(int j=0; j<n; j++) {
for(int k=m-1; k>=i; k--) {
for(int l=n-1; l>=n; l--) {
if(matrixSum(matrix, i, j, k, l)) {
size=(k-i+1)*(l-j+1);
if(size>=sum) sum=size;
}
}
}
}
}
System.out.println(max);
/*******************************************************************************/
public boolean matrixSum(int[][] matrix, int i, int j, int k, int l) {
int sum=0;
for(int a=i; a<=k; a++) {
for(int b=j; b<=l; b++) sum+=matrix[a][b];
}
return sum==0; //will return true or false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment