6*6 数组中可能的最大沙漏总和

Poo*_*ngh 5 c arrays multidimensional-array

有一个关于二维数组的问题说

给定一个 6*6 矩阵,我们必须打印矩阵中找到的最大(最大)沙漏总和。沙漏被描述为:

a b c
  d
e f g
Run Code Online (Sandbox Code Playgroud)

输入样本

1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 0 2 4 4 0
0 0 0 2 0 0
0 0 1 2 4 0
Run Code Online (Sandbox Code Playgroud)

样本输出

19
Run Code Online (Sandbox Code Playgroud)

解释

样本矩阵包含以下沙漏:

1 1 1   1 1 0   1 0 0   0 0 0
  1       0       0       0
1 1 1   1 1 0   1 0 0   0 0 0

0 1 0   1 0 0   0 0 0   0 0 0
  1       1       0       0
0 0 2   0 2 4   2 4 4   4 4 0

1 1 1   1 1 0   1 0 0   0 0 0
  0       2       4       4
0 0 0   0 0 2   0 2 0   2 0 0

0 0 2   0 2 4   2 4 4   4 4 0
  0       0       2       0
0 0 1   0 1 2   1 2 4   2 4 0
Run Code Online (Sandbox Code Playgroud)

总和 (19) 最大的沙漏是

2 4 4
  2
1 2 4
Run Code Online (Sandbox Code Playgroud)

我编写了一个程序,其中创建了一个计算沙漏总和的函数。现在我创建了一个循环,为一行可能的每四个沙漏调用此函数。每四行可以形成一个沙漏。

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

int sum(int a[6][6],int i,int j)
{
    int n=i+3;
    int m=j+3;
    int sum=0;
   for(i;i<n;i++)
   {
       for(j;j<m;j++)
       {
           if(i==n-2)
           {
               sum += a[i][j+1];
               break;
           }
          else
             sum += a[i][j];
       }   
   }
   // printf("%d\t",sum);
    return sum;
}

int main(){
    int arr[6][6];
    int i,j,n,k;
    int max=0;
    for(int arr_i = 0; arr_i < 6; arr_i++){
       for(int arr_j = 0; arr_j < 6; arr_j++){

          scanf("%d",&arr[arr_i][arr_j]);
       }
    }
    for(int i=0;i<4;i++)
    {
        k=0;
        while(k<4)
        {
            n=sum(arr,i,k);
          //  printf("%d\t",n);
            k++;
            if(n>max)
                max=n;

        }
    }
    printf("%d",max);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

谁能告诉我哪里出了问题,或者这个方法对于解决这个问题不正确?

我的程序打印10为输出。

evi*_*ham 3

该错误可能出在您的sum函数中。你这样做的方式有点矫枉过正,对你来说这样做会更简单(并且可读!):

#define GRID_SIZE (6)
int sum(int a[GRID_SIZE][GRID_SIZE], int i, int j)
{   // Define an hourglass by the index i,j of its central element
    int sum = a[j-1][i-1] + a[j-1][i] + a[j-1][i+1] +
                            a[j][i] +
              a[j+1][i-1] + a[j+1][i] + a[j+1][i+1];
    return sum;
}
Run Code Online (Sandbox Code Playgroud)

然后确保使用合理的值进行迭代(在 [1, len-2] 中):

for (int i = 1; i < (GRID_SIZE-1); i++)
{
    for (int j = 1; j < (GRID_SIZE-1); j++)
    {
        n = sum(arr, i, j);
        if (n > max)
            max = n;

    }
}
Run Code Online (Sandbox Code Playgroud)

编辑:检查它是否在这里工作:http://www.cpp.sh/46jhy

谢谢,这很有趣:-)。

PS:请务必检查一些编码标准文档,从长远来看,它会让您的生活变得更加轻松,只需搜索“C 代码格式标准”并习惯于尝试使用您喜欢的标准。除非你自己做一些新的事情,否则你可能必须遵循一个标准,甚至可能对哪个标准没有发言权,所以熟悉一般规则并习惯遵循一个标准,无论你喜欢什么。