最大子阵

给定一个 n×mn \times mn×m 的矩阵 AAA,求 AAA 中的一个非空子矩阵,使这个子矩阵中的元素和最大。其中,AAA 的子矩阵指在 AAA 中行和列均连续的一部分。

输入格式

输入的第一行包含两个整数 n,m(1≤n,m≤50)n,m(1 \leq n,m \leq 50)n,m(1n,m50),分别表示矩阵 AAA 的行数和列数。

接下来 nnn 行,每行 mmm 个整数,表示矩阵 Ai,j(−1000≤Ai,j≤1000)A_{i,j}(-1000 \leq A_{i,j} \leq 1000)Ai,j(1000Ai,j1000)。

输出格式

输出一行,包含一个整数,表示 AAA 中最大子矩阵的元素和。

样例输入

3 3
2 -4 1
-1 2 1
4 -2 2

样例输出

6
 1 package 最大子阵;
 2 
 3 import java.util.Scanner;
 4 
 5 public class 最大子阵 {
 6 
 7     /**
 8      * @param args
 9      */
10     public static void main(String[] args) {
11         // TODO Auto-generated method stub
12         Scanner scan=new Scanner(System.in);
13         int n=scan.nextInt();
14         int m=scan.nextInt();
15         int[][] arr=new int[n][m];
16         for(int i=0;i<n;i++){
17             for(int j=0;j<m;j++){
18                 arr[i][j]=scan.nextInt();
19             }
20         }
21         int max=arr[0][0];
22         for(int begini=0;begini<n;begini++){
23             for(int endi=begini;endi<n;endi++){
24                 for(int beginj=0;beginj<m;beginj++){
25                     for(int endj=beginj;endj<m;endj++){
26                         int sum=0;
27                         for(int i=begini;i<=endi;i++){
28                             for(int j=beginj;j<=endj;j++){
29                                 sum+=arr[i][j];
30                             }
31                         }
32                         if(sum>max&&sum!=0){
33                             max=sum;
34                         }
35                     }
36                 }
37             }
38         }
39         System.out.println(max);
40     }
41 }

 

posted on 2019-02-27 13:31  JJ今天开心了吗  阅读(194)  评论(0)    收藏  举报

导航