Maximum hourglass sum possible in a 6*6 array

前端 未结 3 1420
北荒
北荒 2021-01-14 08:27

There is a question on 2D array which says

Given a 6*6 matrix we have to print the largest (maximum) hourglass sum found in the matrix. An hourglass is described as:

3条回答
  •  北荒
    北荒 (楼主)
    2021-01-14 09:30

    #include 
    
    int main() {
        int numbers[6][6];
        for (int i = 0; i < 6; i++){
            for (int j = 0; j < 6; j++){
                scanf("%d",&numbers[i][j]);
            }
        }
        int currentHourGlass;
        int largestSum = -999;
    
        for (int i = 1; i < 5; i++){
            for (int j = 1; j < 5; j++){
                currentHourGlass = 0;
                currentHourGlass += numbers[i-1][j-1];
                currentHourGlass += numbers[i-1][j];
                currentHourGlass += numbers[i-1][j+1];
                currentHourGlass += numbers[i][j];
                currentHourGlass += numbers[i+1][j-1];
                currentHourGlass += numbers[i+1][j];
                currentHourGlass += numbers[i+1][j+1];
                
                if (currentHourGlass > largestSum)
                {
                    largestSum = currentHourGlass;
                }
    
            }
        }
    
       printf("%d", largestSum);
    

    }

提交回复
热议问题