1. 程式人生 > >2D Array —— HourGlassSum(C#)

2D Array —— HourGlassSum(C#)

沙漏的定義

在一個二位陣列中,我們將形如下面示例的數字集合成為沙漏。

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