当前位置:   article > 正文

Java实现子矩阵的和(前缀和)_求矩阵所有子矩阵价值之和java编程

求矩阵所有子矩阵价值之和java编程
import java.util.*;

public class Main{
    static int N = 1005;
    static int[][] f = new int[N][N];
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();//n行
        int m = in.nextInt();//m列
        int q = in.nextInt();//查询矩阵个数
        for(int i=1;i<=n;i++){
            for(int j=1;j<=m;j++){
                int x = in.nextInt();
                f[i][j]=f[i-1][j]+f[i][j-1]-f[i-1][j-1]+x;
            }
        }
        for(int i=1;i<=q;i++){
            int res=0;
            int x1 = in.nextInt();//矩阵开始坐标
            int y1 = in.nextInt();
            int x2 = in.nextInt();//结束坐标
            int y2 = in.nextInt();
            //System.out.println(f[x2][y2]+" "+f[x1-1][y2]+" "+f[x2][y1-1]);
            res+=(f[x2][y2]-f[x1-1][y2]-f[x2][y1-1]+f[x1-1][y1-1]);//要加上重复减去的
            System.out.println(res);
        }
        
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/煮酒与君饮/article/detail/871440
推荐阅读
相关标签
  

闽ICP备14008679号