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.
Example
Given matrix
[
[1 ,5 ,7],
[3 ,7 ,-8],
[4 ,-8 ,9],
]
return [(1,1), (2,2)]
这个题其实有点brain fuck。。锁定sum=0的submatrix是通过扫所有的左上角submatrix的差值去确定的。在i 上下界确定情况下,如果存在俩个submatrix sum一样,必然其差值部分的submatrix的sum=0
用到辅助矩阵sum matrix(纪录左上角矩阵和)
凡是用到需要额外计算的辅助变量的题目都比较难想,这个题tricky程度挺高
public int[][] submatrixSum(int[][] matrix) {
// Write your code here
int[][] res = new int[2][2];
if(matrix == null || matrix.length == 0|| matrix[0].length == 0)
return res;
int n = matrix.length;
int m = matrix[0].length;
//A challenge about this question is to notice sum matrix should be [n+1] *[m+1]
//beforehand
int[][] sum = new int[n+1][m+1];
for(int i=1; i<=n; i++){
for(int j=1; j<=m; j++){
sum[i][j] = matrix[i-1][j-1] + sum[i-1][j] + sum[i][j-1] - sum[i-1][j-1];
}
}
//This way actually is fcking tricky without knowing beforehand.
for(int i=0; i<=n; i++){
for(int h=i+1; h<=n; h++){
HashMap
map = new HashMap
();
for(int j=0; j<=m; j++){
int diff = sum[h][j] - sum[i][j];
if(map.containsKey(diff)){
res[0][0] = i; res[0][1] = map.get(diff);
res[1][0] = h-1; res[1][1] = j-1;
return res;
}else{
map.put(diff,j);
}
}
}
}
return res;
}