二维数组最大子数组和
生活随笔
收集整理的這篇文章主要介紹了
二维数组最大子数组和
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一.實驗題目
求一個二維數組中和最大的子數組。
二.實驗思路
基于我們第一次合作時求的一位數組最大子數組,加上一層循環來遍歷二維數組中的所有子矩陣的情況。
第一步:先利用上次的方法求每一行的情況,將每行結果存入一個一位數組中,構成一個二維數組A[][]。
第二步:將上述二維數組每一列利用求每一行的方法再次遍歷。將每個結果與A[][]中的值比較取大值。
第三步:輸出這個最大值。
三.代碼
1 // ketang5.cpp : 定義控制臺應用程序的入口點。 2 //人員: 張世通 梁世豪 3 4 #include "stdafx.h" 5 #include "iostream" 6 #include "fstream" 7 using namespace std; 8 9 /*二維數組壓縮函數*/ 10 void yasuo(int **Source,int **Destion,int row,int line) 11 {//將每一行的數組元素都用枚舉法求出子數組 12 int i,j,add,count; 13 for(i=0;i<row;i++) 14 { 15 count=0; 16 for(j=0;j<line;j++) 17 { 18 add=0; 19 for(int l=0;l<line-j;l++) //每一行按順序進行枚舉存入數組中 20 { 21 add=add+Source[i][j+l]; 22 Destion[i][count+l]=add; 23 } 24 count=count+line-j; 25 } 26 } 27 } 28 29 /*求最大值函數*/ 30 int Max(int **Destion,int row,int line) 31 { 32 int i,j,add,max; 33 max=Destion[0][0]; //將數組的第一個數賦值給max 34 for(j=0;j<line;j++) 35 { 36 for(i=0;i<row;i++) 37 { 38 add=0; 39 for(int r=0;r<row-i;r++) 40 { 41 add=add+Destion[r+i][j]; //逐列對數組進行枚舉,求最大值 42 if(max<add) 43 { 44 max=add; 45 } 46 } 47 } 48 } 49 return max; 50 } 51 52 /*數組初始化*/ 53 void chushihua(int**Arr,int row,int line) 54 { 55 cout<<"請輸入數組數據"<<endl; 56 for(int i=0;i<row;i++) 57 { 58 for(int j=0;j<line;j++) 59 { 60 cin>>Arr[i][j]; 61 } 62 } 63 } 64 65 /*釋放空間*/ 66 void Delete(int **Arr,int row) 67 { 68 for(int i=0;i<row;i++) 69 { 70 delete[]Arr[i]; 71 } 72 delete[]Arr; 73 } 74 int main() 75 { 76 char s; 77 int row,col1,col2; //定義行數列數 78 cout<<"請輸入行數:"; 79 cin>>row; 80 cout<<"請輸入列數:"; 81 cin>>col1; 82 int **A; //動態定義二維數組 83 int **B; 84 col2=col1*(col1+1)/2; 85 A=new int*[row]; 86 for(int k=0;k<row;k++) 87 { 88 A[k]=new int[col1]; 89 } 90 B=new int*[row]; 91 for(int l=0;l<row;l++) 92 { 93 B[l]=new int[col2]; 94 } 95 chushihua(A,row,col1); 96 yasuo(A,B,row,col1); 97 int max=Max(B,row,col2); 98 cout<<"最大子數組之和為:"<<max<<endl; 99 cout<<endl; 100 cout<<"是否繼續(Y/N)"; 101 cin>>s; 102 while(s!='Y'&&s!='y'&&s!='N'&&s!='n') 103 { 104 cout<<"輸入錯誤,請重新輸入(Y/N)"; 105 cin>>s; 106 } 107 if(s=='Y'||s=='y') 108 { 109 main(); 110 } 111 else //釋放數組空間 112 { 113 Delete(A,row); 114 Delete(B,row); 115 } 116 return 0; 117 }四.運行截圖
?
五.收獲體會
第一點,這次結對開發的過程讓我學會了利用已有資源進行程序的開發,正是有了上次一位數組求最大子數組的基礎,這次求二維數組最大子數組才有了正確的思路。
?
第二點,這是和世通的第二次結對開發程序,他的思路很清晰,編程能力也很好,有很多值得我學習的地方。以后應該還有很多合作的機會,我都會珍惜的。
?
第三點,我覺得結對開發這個主意應該早點應用到我們的學習中,這種方法下我們會盡力去思考問題的解決方法,基礎差一點的在另一方的影響下也會學到不少實用的東西。而不是遇見不會的就百度一個程序去應付老師而造成惡性循環,給自己扣上一個“不會編程”的帽子來逃避。
六.合影
轉載于:https://www.cnblogs.com/zglsh/p/4369598.html
總結
以上是生活随笔為你收集整理的二维数组最大子数组和的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: struts2--文件上传大小
- 下一篇: 移动设备和SharePoint 2013