设计思路:
从第一行到最后一行将连续行的元素对应相加,得到一个一维数组,再利用一维数组求最大子数组和大方法,求得最大子矩阵
实验代码:
package sum; import java.util.Scanner; public class sum { //public static int row = 3,col = 4; //对i到j行求和,返回一个一维数组 static int[] sum_i_j(int data[][],int cols,int i,int j) { int sum[]=new int[cols]; for(int n = 0;n<sum.length;n++) { sum[n]=0; } for(int col=0;col<cols;col++){ for(int row=i;row<=j;row++){ sum[col]+=data[row][col]; } } return sum; } //求每一个一维数组的最大值 static int maxSum(int arr[],int sz){ { if (arr == null || sz < 1) return 0; int MAX = arr[0]; int sum = arr[0]; for (int i = 1; i < sz; i++) { if (sum < 0) sum = arr[i]; else { sum += arr[i]; } if (sum > MAX) MAX = sum; } return MAX; } } // static int maxSubSum(int data[][],int rows,int cols){ int max=-0x3f3f3f3f; int sumTmp[]=new int[cols]; for(int i=0;i<rows;i++){ for(int j=i;j<rows;j++){ sumTmp=sum_i_j(data,cols,i,j); int tmp=maxSum(sumTmp,cols); if(tmp>max){ max=tmp; } } } return max; } public static void main(String[] args){ Scanner input=new Scanner(System.in); System.out.println("请输入二维数组的行与列:"); int row=input.nextInt(); int col=input.nextInt(); // input.close(); int a[][] = new int[row][col]; // 随机赋值 System.out.println("总矩阵为"); for(int i = 0;i < row;i++){ for(int j = 0;j < col;j++){ // int x=input.nextInt(); //a[i][j]=x; a[i][j] = (int)(Math.random() * 20 - 10); if(a[i][j] >= 0) System.out.print(" "); System.out.print(a[i][j] + " "); } System.out.print(" "); } input.close(); System.out.println("最大子矩阵的和为"); System.out.println(maxSubSum(a, row, col)); } }
实验截图: