一.题目
返回一个二维整数组中最大联通子数组的和
二.题目要求:
1.输入一个二维数组,数组里既有正数也有复数
2.求所有子数组的和的最大值
三.设计思路:
首先将二维数组中正整数的值找出来,之后找到每个正整数上下左右加起来为正的负数。之后判断是否联通,将小的负数排除掉,最后留下的是二维整数数组中最大联通子数组。
四。结对开发伙伴:
姓名:程思敏
博客名:鹏程万里之思
博客地址链接:http://home.cnblogs.com/u/pengchengwanli/
五.代码:
//2016 4 2 王宗泽 程思敏 #include <iostream> #include <time.h> #define M 3 #define N 5 using namespace std; void main() { int a[M][N] = {0},b[M][N]={0}; //判断联通性,0为未选中,1为选中,2为连通 bool flg = 0; //判断是否有1存在,存在为O。 int sum = 0; //最后和 srand(unsigned((int)time(0))); for (int i = 0;i < M;i++) { for (int j = 0;j < N;j++) { a[i][j] = rand()%50 - 20; cout << a[i][j] << " "; if (a[i][j] >= 0) { b[i][j] = 1; } } cout << endl; } cout << endl; for (int i = 0;i < M;i++) { for (int j = 0;j < N;j++) { if (b[i][j] == 1) { if (a[i+1][j] + a[i][j] > 0 && b[i+1][j] == 0) { b[i+1][j] = 2; } if (a[i-1][j] + a[i][j] > 0 && b[i-1][j] == 0) { b[i-1][j] = 2; } if (a[i][j-1] + a[i][j] > 0 && b[i][j-1] == 0) { b[i][j-1] = 2; } if (a[i][j+1] + a[i][j] > 0 && b[i][j+1] == 0) { b[i][j+1] = 2; } } } } for (int i = 0;i < M;i++) { for (int j = 0;j < N;j++) { flg = 0; if (b[i][j] != 0 && a[i][j] < 0) { b[i][j] = 0; for (int k = 0;k < M;k++) { for (int l = 0;l < N;l++) { if (b[k][l] != 0) { if ((b[k+1][l] <= 0 || b[k+1][l] > 2)&& (b[k-1][l] <= 0 || b[k-1][l] > 2)&& (b[k][l+1] <= 0 || b[k][l+1] > 2)&& (b[k][l-1] <= 0 || b[k][l-1] > 2)) { flg = 1; } } } } if (flg) { b[i][j] = 2; } } } } for (int i = 0;i < M;i++) { for (int j = 0;j < N;j++) { if (b[i][j] != 0) { cout << a[i][j] << " "; sum += a[i][j]; } else { cout << "**" << " "; } } cout << endl; } cout << "sum = " << sum << endl; }
六.运行结果: