寻找最大的2x2" square"数组C中的值

时间:2015-03-26 19:23:44

标签: c arrays algorithm

对于我的作业,我必须接受一组数值,将它们保存到第二个数组并打印出4个最高值的“正方形”。这意味着“square”,其元素之和在数组中最大。

Example:  Given the array    1    2    3     4
                             5    6    7     8
                             9    10   11   12     

 the output should be       7      8      
                            11    12 

我最初尝试使用嵌套for循环集来查找并将每个后续最大值存储到第二个数组中,但似乎无法找出正确的算法。到目前为止,我只给了我相同的值(在这个例子中,12)。另外,我已经意识到这种方式不允许我在第二个数组中保持格式相同。

我的意思是,如果我保存在数组b [0] [0]中找到的最大数字,它将在错误的位置,我的方块将关闭,看起来像:

12 11
10 9

这是我到目前为止所拥有的:

int main(){

int og[3][4]={{1,2,3,4},{5,6,7,8},{9,10,11,12}}, new[2][2]={}, rows;
int columns, i, high,j,high2,high3,high4;

high = new[i][0];
high2= high - 1;
high3= high2 - 1;
high4= high3 - 1;
rows = 3;
columns = 4;

for (i=0; i<=rows; i++){
    for(j=0; j<=columns; j++){
        if (high < og[j][i])
        high = og[j][i];            
    }        
}

for(i=1;i<=rows;i++){
    for(j=1;j<=columns;j++){
        if(high2 < og[j][i])
        high2= og[j][i];
    }
}
printf("max = %d, %d\n", high, high2);
//return high;
system("pause");
return 0;

3 个答案:

答案 0 :(得分:9)

逻辑应该大致如下(我没有编译器atm来测试它,所以如果我做了一个derpy错误,请在评论中告诉我):

int i = 0;
int j = 0;
int max = 0;
int sum = 0;
int i_saved = 0;
int j_saved = 0;

for(i = 0; i < rows - 1; i++){
   for(j =0; j < columns -1; j++){
       sum = og[i][j] + og[i][j+1] + og[i+1][j] + og[i+1][j+1]; //sum the square
       if (sum > max){
         max = sum;
         i_saved = i;
         j_saved = j;
       }
   }
}

由于OP要求使用的值以便保存到另一个数组,所以您只需要再次检索这些值!我们已经保存了索引,所以这应该是相对微不足道的。

int [][] arr = [2][2];
arr[0][0] = og[i_saved][j_saved];
arr[0][1] = og[i_saved][j_saved+1];
arr[1][0] = og[i_saved+1][j_saved];
arr[1][1] = og[i_saved+1][j_saved+1];

我们总结它们的方式相同,我们也可以使用该逻辑模式来提取它们!

答案 1 :(得分:1)

我创建了这个解决方案:

#include <iostream>
#include <algorithm>

using namespace std;

int main()
{

    int Mat[3][4]={{1,  2,  3,  4},
                  {5,  6,  7,  8},
                  {9, 10, 11, 12}};

    int maximum = 0;
    int Max_2x2[2][2] = {{1, 2},
                         {5, 6}};


    for(int i = 0; i < 2; i++) {
        for(int j = 0; j < 3; j++) {
            maximum = max(Mat[i][j]+Mat[i][j+1]+Mat[i+1][j]+Mat[i+1][j+1], maximum);
            if(maximum == Mat[i][j]+Mat[i][j+1]+Mat[i+1][j]+Mat[i+1][j+1]) {
                Max_2x2[0][0] = Mat[i][j];
                Max_2x2[0][1] = Mat[i][j+1];
                Max_2x2[1][0] = Mat[i+1][j];
                Max_2x2[1][1] = Mat[i+1][j+1];
            }

        }
    }
    cout << maximum << endl;
    for(int i = 0; i < 2; i++) {
        for(int j = 0; j < 2; j++) {
            cout << Max_2x2[i][j] << " ";
        }
        cout << endl;
    }

    return 0;
}

给出以下输出:

38   // maximum solution
7 8  // output array
11 12 

这显然不是一般解决方案,但它适用于您的示例。

答案 2 :(得分:-2)

int new[2][2]={}

我不确定这是否有效。您可能需要为每个单元格指定0值。即使它不是必需的,这也是很好的做法。

high = new[i][0];

我没有看到i已初始化的位置。

相关问题