9.子矩阵的和

思想:

前缀和思想相同,只不过子矩阵的和转化为二维。


重点:

首先了解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]);
        }
    }

}

 

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值