"Returns the number of the largest interconnected subarray in a two-dimensional integer array"
Design idea: (1) Firstly, this two-dimensional array is decomposed into a one-dimensional array with the same number of columns as the number of rows;
(2) The sum of the maximal contiguous subarray of these one-dimensional arrays is calculated separately, and the first and last positions of each maximal continuous array are recorded respectively;
(3) Then compare the first and last position of these one-dimensional arrays are in the matrix connected to the position, find the position and the largest array, and output their sum.
Source:
#include <iostream>using namespacestd;intMax (intNintA[],int*smark,int*Mmark) { intb[ -]={0}; inti,sum1=0, max1=0; for(i=0; i<n;i++) { if(sum1<0) {sum1=A[i]; } Else{sum1=sum1+A[i]; } B[i]=sum1; } max1=b[0]; for(i=0; i<n;i++) { if(max1<B[i]) {Max1=B[i]; *mmark =i; } } for(i = *mmark;i >=0; i--) { if(B[i] = =A[i]) { *smark =i; Break; } } returnMax1;} voidMain () {intm,n,i,j,smark,mmark,t2; intsum; intup[ -],down[ -],t[ -]; inta[ -][ -],b[ -]; cout<<"Please enter the number of rows and columns of the two-dimensional array:"; CIN>>m>>N; cout<<"Please enter this two-dimensional matrix:"<<Endl; for(i=0; i<m;i++) { for(j=0; j<n;j++) {cin>>A[i][j]; } } //decompose a two-dimensional array into several one-dimensional arrays by rows for(i=0; i<m;i++) { for(j=0; j<n;j++) {B[j]=A[i][j]; } Sum=max (n,b,&smark,&Mmark); Up[i]=Smark; Down[i]=Mmark; T[i]=sum; } T2=t[0]; for(i=0; i+1<m;i++) { if(up[i]<=down[i+1] && down[i]>=up[i+1]) {T2+=t[i+1]; } for(j=up[i];j<up[i+1];j++) { if(a[i+1][j]>0) t2+=a[i+1][J];//distinguishing independent positive numbers}} cout<<t2<<Endl;}
Experimental results:
Programming Summary: Although understand the requirements of the topic, but also understand the input what should be obtained after what results, but in the design algorithm is still encountered a certain difficulty, always enter a dead end after the solution can not find the method, which wrote this program dragged for a long time, Then in reference to other people's ideas and the help of the students are basically completed the task, so I think I do not have a good solution to the idea and method is because the usual practice too little, thinking stalled, so more practice, see more, more relevant information, learn a good idea is I need to step in depth in the future!
"Returns the number of the largest interconnected subarray in a two-dimensional integer array"