Given an integer matrix, find a submatrix where the sum of numbers is zero. Your code should return the coordinate of the left-up and right-down number.
Copy [
[1 ,5 ,7],
[3 ,7 ,-8],
[4 ,-8 ,9],
]
Copy sumY[i][j] = i-1 < 0 ? 0 : sumY[i-1][j] + matrix[i][j];
Copy sumY[i][j] = i-1 < 0 ? 0 : sumY[i-1][j] + matrix[i][j];
sum[i][j] = sum[i][j-1] + sumY[i-1][j-1];
Copy sum[i+1][j+1] = matrix[i][j] + sum[i+1][j] + sum[i][j+1] - sum[i][j];
Copy public int[][] submatrixSum(int[][] matrix) {
// Write your code here
if(matrix == null || matrix.length == 0 || matrix[0] == null || matrix[0].length == 0)
return null;
int n = matrix.length;
int m = matrix[0].length;
int[][] ret = new int[2][2];
int[][] sumY = new int[n][m];
int[][] sum = new int[n+1][m+1];
for(int j = 0; j < m; j++)
{
for(int i = 0; i < n; i++){
sumY[i][j] = i-1 < 0 ? 0 : sumY[i-1][j] + matrix[i][j];
}
}
for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= m; j++){
sum[0][j] = 0;
sum[i][j] = sum[i][j-1] + sumY[i-1][j-1];
}
}
// int n = matrix.length;
// int m = matrix[0].length;
// int[][] ret = new int[2][2];
// // pre-compute: sum[i][j] = sum of submatrix [(0, 0), (i, j)]
// int[][] sum = new int[n+1][m+1];
// for (int j=0; j<=m; ++j) sum[0][j] = 0;
// for (int i=1; i<=n; ++i) sum[i][0] = 0;
// for (int i=0; i<n; ++i) {
// for (int j=0; j<m; ++j)
// sum[i+1][j+1] = matrix[i][j] + sum[i+1][j] + sum[i][j+1] - sum[i][j];
// }
for(int l = 0; l < n; l++)
{
for(int h = l + 1; h <= n; h++){
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int j = 0; j <= m; j++){
int diff = sum[h][j] - sum[l][j];
if(map.containsKey(diff)){
int k = map.get(diff);
ret[0][0] = l;
ret[0][1] = k;
ret[1][0] = h-1;
ret[1][1] = j-1;
}else{
map.put(diff, j);
}
}
}
}
return ret;
}