思想:
前缀和思想相同,只不过子矩阵的和转化为二维。
重点:
首先了解s [ i ][ j ] 指的是什么?
找到二维矩阵的第 i 行,第 j 列。其左上角所有元素的和即为 s [ i ][ j ]。
怎么计算s [ i ][ j ] ?
以下图举例:
1.首先计算 s[ i - 1 ][ j ] 为绿色部分
2.再加上 s [ i ][ j - 1 ] 的绿色部分
3.得到的图像深绿色部分为相加重复的部分,需要减去,深绿色部分为 s [ i - 1 ][ j - 1 ]
4.最后加上 a[ i ][ j ]点为最终的s [ i ][ j ]
最终计算:
s [ i ][ j ] = s [ i - 1 ][ j ] + s [ i ][ j - 1 ] - s [ i - 1 ][ j - 1] + a [ i ][ j ]
求最终的子矩阵也是使用相同的思想
代码如下:
package cn.liyi.day05;
import java.util.Scanner;
public class Demo796 {
public static int N = 10010;
public static int[][] a = new int[N][N];
public static int[][] s = new int[N][N];
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入矩阵的行数和列数:");
int n = sc.nextInt();
int m = sc.nextInt();
System.out.println("请输入矩阵的元素:");
for (int i = 1; i <= n; i ++)
for (int j = 1; j <= m; j ++)
a[i][j] = sc.nextInt();
for (int i = 1; i <= n; i ++)
for(int j = 1; j <= m; j ++)
s[i][j] = s[i - 1][j] + s[i][j - 1] - s[i - 1][j - 1] + a[i][j];
System.out.println("请输入询问次数:");
int p = sc.nextInt();
while (p -- > 0) {
System.out.println("请输入边界:");
int x1 = sc.nextInt();
int y1 = sc.nextInt();
int x2 = sc.nextInt();
int y2 = sc.nextInt();
System.out.println(s[x2][y2] - s[x1 - 1][y2] - s[x2][y1 - 1] + s[x1 - 1][y1 - 1]);
}
}
}