設計思路:
首先将二維數組中正整數的值找出來,之後找到每個正整數上下左右加起來為正的負數。之後判斷是否聯通,将小的負數排除掉,最後留下的是二維整數數組中最大聯通子數組。
程式代碼:
1 #include <iostream>
2 #include <time.h>
3 #define M 3
4 #define N 5
5 using namespace std;
6
7 void main()
8 {
9 int a[M][N] = {0},b[M][N]={0};//判斷聯通性,0為未選中,1為選中,2為連通
10 bool flg = 0; //判斷是否有1存在,存在為O。
11 int sum = 0; //最後和
12
13 srand(unsigned((int)time(0)));
14 for (int i = 0;i < M;i++)
15 {
16 for (int j = 0;j < N;j++)
17 {
18 a[i][j] = rand()%50 - 20;
19 cout << a[i][j] << "\t";
20 if (a[i][j] >= 0)
21 {
22 b[i][j] = 1;
23 }
24 }
25 cout << endl;
26 }
27 cout << endl;
28
29 for (int i = 0;i < M;i++)
30 {
31 for (int j = 0;j < N;j++)
32 {
33 if (b[i][j] == 1)
34 {
35 if (a[i+1][j] + a[i][j] > 0 && b[i+1][j] == 0)
36 {
37 b[i+1][j] = 2;
38 }
39 if (a[i-1][j] + a[i][j] > 0 && b[i-1][j] == 0)
40 {
41 b[i-1][j] = 2;
42 }
43 if (a[i][j-1] + a[i][j] > 0 && b[i][j-1] == 0)
44 {
45 b[i][j-1] = 2;
46 }
47 if (a[i][j+1] + a[i][j] > 0 && b[i][j+1] == 0)
48 {
49 b[i][j+1] = 2;
50 }
51 }
52 }
53 }
54
55 for (int i = 0;i < M;i++)
56 {
57 for (int j = 0;j < N;j++)
58 {
59 flg = 0;
60 if (b[i][j] != 0 && a[i][j] < 0)
61 {
62 b[i][j] = 0;
63 for (int k = 0;k < M;k++)
64 {
65 for (int l = 0;l < N;l++)
66 {
67 if (b[k][l] != 0)
68 {
69 if ((b[k+1][l] <= 0 || b[k+1][l] > 2)&&
70 (b[k-1][l] <= 0 || b[k-1][l] > 2)&&
71 (b[k][l+1] <= 0 || b[k][l+1] > 2)&&
72 (b[k][l-1] <= 0 || b[k][l-1] > 2))
73 {
74 flg = 1;
75 }
76 }
77 }
78 }
79 if (flg)
80 {
81 b[i][j] = 2;
82 }
83 }
84 }
85 }
86
87 for (int i = 0;i < M;i++)
88 {
89 for (int j = 0;j < N;j++)
90 {
91 if (b[i][j] != 0)
92 {
93 cout << a[i][j] << "\t";
94 sum += a[i][j];
95 }
96 else
97 {
98 cout << "**" << "\t";
99 }
100 }
101 cout << endl;
102 }
103
104 cout << "sum = " << sum << endl;
105 }
結果截圖:
總結:
這個開始想思路的時候就感覺很難,程式設計的時候發現的确如此。實作的結果并不理想。雖然結果大部分會對,可是還是有一部分bug,本來是在往後補漏洞,修改,可是越補越多,感覺不應該這樣。目前隻能這樣了。