Design ideas:
The two-dimensional array of n*m is decomposed, decomposed into n one-dimensional arrays, and then the largest subarray of n one-dimensional arrays and note the subscript of the largest one-dimensional sub-array of each row, such as 2-5, which is divided into two cases the first is the largest sub-array between rows is connected, such as the first row is 2-5, the second row is 3-6, This is directly added to the line. The second is not connected, such as the first row is 2-5, the second row is 6-7, this time the largest sub-array of each row as a whole, and then make each of the largest array of blocks connected, so that the minimum cost of its connection. Finally, we can find out the maximum number of interconnected sub-arrays. Code:
Mport Java.awt.Point; Import Java.util.Scanner; public class Main {public static int add (int a[][],int i,int j,int k) {int n; int b=0; for (n=j;n<=i+j;n++) {b+=a[n][k]; } return B; } public static void Main (string[] args) {//TODO auto-generated method stub int i,j,k,l; int sum=0,s,h,e; Point Head=new Point (); Point End=new Point (); Scanner sc=new Scanner (system.in); System.out.print ("Please enter the number of rows in the matrix:"); int X=sc.nextint (); System.out.print ("Please enter the number of columns of the Matrix:"); int Y=sc.nextint (); int a[][]=new Int[x][y]; int b[]=new Int[y]; System.out.println ("Please enter the number in the array:"); for (i=0;i<x;i++) {for (j=0;j<y;j++) {a[i][j]=sc.nextint (); }} for (i=0;i<x;i++) {for (j=0;i+j<x;j++) {s=0; h=0; e=0; for (k=0;k<y;k++) {b[k]=add (a,i,j,k); } for (l=0;l<x;l++) {s+=b[l]; if (s>0) {e++; } else {s=0; h=l+1; e++; } if (s>sum) {sum=s; Head.x=h; Head.y=j; End.x=e; End.y=i+j; }} if (s>0&&h!=0) {l=0; E=e-x; while (s>0&&e!=h-1) {s+=b[l]; l++; e++; if (s>sum) {sum=s; Head.x=h; Head.y=j; End.x=e; End.y=i+j; }}}}} System.out.print ("The maximum number of sub-arrays is:"); SYSTEM.OUT.PRINTLN (sum); SYSTEM.OUT.PRINTLN ("Maximum sub-array is:"); if (end.x>head.x) {for (i=head.y;i<=end.y;i++) {for (J=HEAD.X;J&L t;end.x;j++) {System.out.print (a[i][j]); System.out.print (""); } System.out.println (); }} else {for (i=head.y;i<=end.y;i++) {for (j=head.x;j<x;j++) { System.out.print (A[i][j]); System.out.print (""); } for (j=0;j<end.x;j++) {System.out.print (a[i][j]); System.out.print (""); } System.out.println (); } } } }
Summarize:
Learn to switch ideas, talk a big problem into a few small problems, slowly solve, a piece of solution.
:
A two-dimensional array of maximal connected sub-arrays