2D Array —— HourGlassSum(C#)

版权声明:版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/shaotaiban1097/article/details/82017230

沙漏的定义

在一个二位数组中,我们将形如下面示例的数字集合成为沙漏。

a b c
  d
e f g

例如:

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

共拥有16组沙漏(具体见题目末尾图)

每个沙漏的数字和称之为沙漏和(hourglass sum)


For Example:

Function Description

Complete the function hourglassSum in the editor below. It should return an integer, the maximum hourglass sum in the array.

hourglassSum has the following parameter(s):

  • arr: an array of integers

Input Format

Each of the 6 lines inputs a r r [ i ] contains 6 space-separated integers a r r [ i ] [ j ] .

Constraints

  • 9 a r r [ i ] [ j ] 9
  • 0 i , j 5

Output Format

Print the largest(maximum) hourglass sum found in arr.

Sample Input

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

Sample Output

19

Explanation

arr contains the following hourglasses

hourglasses


using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text.RegularExpressions;
using System.Text;
using System;

class Solution {

    // the hourglassSum function.
    static int hourglassSum(int[][] arr) {

        //取二维数组中子数组的个数
        int length = arr.Length;
        //初始化hourglassSum和sum,sum用来临时存储每次计算的沙漏和,hourglassSum用来存储目前最大的和
        int sum = 0;
        int hourglassSum = 0;
        //遍历数组的非边缘数字(即可以成为沙漏中心的数字)
        for (int j = 1; j < length - 1; j++){
            for (int i = 1; i < arr[j].Length - 1; i++){
                //当前沙漏数字的和
                sum = arr[i-1][j-1] + arr[i-1][j] + arr[i-1][j+1] + arr[i][j] + arr[i+1][j-1] + arr[i+1][j] + arr[i+1][j+1];
                //第一次将和直接赋值给hourglassSum,防止所有hourglassSum都小与0的情况
                if (i == 1 && j == 1){
                   hourglassSum = sum;
                }
                //当前的沙漏和与目前最大的比较,hourglassSum存储较大的一个
                hourglassSum = sum > result ? sum : result;
            }
        }

        return hourglassSum;               
    }

    static void Main(string[] args) {
        //初始化二维数组
        int[][] arr = new int[][] {new int[]{1, 1, 1, 0, 0, 0},
                                       new int[]{0, 1, 0, 0, 0, 0},
                                       new int[]{1, 1, 1, 0, 0, 0},
                                       new int[]{0, 0, 2, 4, 4, 0},
                                       new int[]{0, 0, 0, 2, 0, 0},
                                       new int[]{0, 0, 1, 2, 4, 0}};
        //调用函数
        int result = hourglassSum(arr);
        //输出结果
        Console.WriteLine(result);
        Console.ReadKey();
    }
}



Expected Output : 19

猜你喜欢

转载自blog.csdn.net/shaotaiban1097/article/details/82017230