给一个matrix, all elements are positive,问有没有个sub rectangle加起来和等于target。return true/false。
package matrix;
import java.util.*;
public class SubMatrixSum {
// http://www.1point3acres.com/bbs/forum.php?mod=viewthread&tid=164888&extra=page%3D6%26filter%3Dsortid%26sortid%3D311%26searchoption%255B3046%255D%255Bvalue%255D%3D2%26searchoption%255B3046%255D%255Btype%255D%3Dradio&page=1
// http://www.1point3acres.com/bbs/forum.php?mod=viewthread&tid=167234&pid=2505700&page=1&extra=page%3D5%26filter%3Dsortid%26sortid%3D311%26searchoption%255B3046%255D%255Bvalue%255D%3D2%26searchoption%255B3046%255D%255Btype%255D%3Dradio#pid2505700
public static void main(String[] args) {
int[][] matrix = { { 3, 5, 6, 7 }, { 4, -2, 14, 3 }, { 5, -10, -2, 7 }, { 6, 15, -21, 4 } };
submatrixSum(matrix, 23);
}
public static int[][] submatrixSum(int[][] matrix, int target) {
int[][] result = new int[2][2];
int M = matrix.length;
if (M == 0)
return result;
int N = matrix[0].length;
if (N == 0)
return result;
// pre-compute: sum[i][j] = sum of submatrix [(0, 0), (i, j)]
int[][] sum = new int[M + 1][N + 1];
for (int j = 0; j <= N; ++j)
sum[0][j] = 0;
for (int i = 1; i <= M; ++i)
sum[i][0] = 0;
for (int i = 0; i < M; ++i) {
for (int j = 0; j < N; ++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 < M; ++l) {
for (int h = l + 1; h <= M; ++h) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int j = 0; j <= N; ++j) {
// int diff = sum[h][j] - sum[l][j];
// if (map.containsKey(diff - target)) {
// int k = map.get(diff - target);
int diff = sum[h][j] - sum[l][j];
if (map.containsKey(diff - target)) {
int k = map.get(diff - target);
result[0][0] = l;
result[0][1] = k;
result[1][0] = h - 1;
result[1][1] = j - 1;
return result;
} else {
map.put(diff, j);
}
}
}
}
return result;
}
}