无法获得沙漏算法的精确结果

时间:2016-11-23 11:44:56

标签: java arrays algorithm array-algorithms

以下是沙漏问题定义的链接: https://www.hackerrank.com/challenges/30-2d-arrays

我写了以下程序:

package day11;

import java.util.Scanner;

public class Solution {

    public static void main(String ... args){

        Scanner scan = new Scanner(System.in);

        int[][] arr = new int[6][6];

        int maxHourGlassValue = 0;
        int temp = 0;
        int currMax = 0;

        int k = 0, l = 0;

        for(int i = 0 ; i < 6 ; i++){
            for(int j = 0 ; j < 6 ; j++){
                arr[i][j] = scan.nextInt();
            }
        }

        for(int i = 1 ; i < 5 ; i++){
            for(int j = 1 ; j < 5 ; j++){
                    if(maxHourGlassValue < currMax){
                    maxHourGlassValue = currMax;
                }
            }


        }

        System.out.println(maxHourGlassValue);

    }

}

我只能运行8个测试用例中的6个。什么可能出错????

2 个答案:

答案 0 :(得分:1)

试试这段代码,我没有写那段代码,我只是复制它并从here修改它

 Set basket = link.Execute("SELECT * FROM Table1;")

答案 1 :(得分:0)

以下是hourglass problem的所有测试用例成功运行的代码。

public static void main(String[] args) {
    try (Scanner scan = new Scanner(System.in)) {
        int[][] arr = new int[6][6];

        int maxHourGlassValue = -63;//Assigning (-9*7=)-63 which is the minimum possible value of "hourglass sum".

        //Reading inputs.
        for (int i = 0; i < 6; i++) {
            for (int j = 0; j < 6; j++) {
                arr[i][j] = scan.nextInt();
            }
        }

        //Logic.
        /**
         * Index of both i and j will run from 1 to 4 (one less than n-1 where n = 6)
         * So for each i and j iteration calculating the sum of hourglass.
         */
        int iHGValueTemp = 0;
        for (int i = 1; i < 5; i++) {
            for (int j = 1; j < 5; j++) {
                iHGValueTemp = arr[i][j] + /*Main element*/
                        arr[i - 1][j - 1] + arr[i - 1][j] + arr[i - 1][j + 1]+ /*Top three elements of main element.*/
                        arr[i + 1][j - 1] + arr[i + 1][j] + arr[i + 1][j + 1]; /*Bottom three elements of main element.*/
                if (iHGValueTemp > maxHourGlassValue) {
                    maxHourGlassValue = iHGValueTemp;
                }
            }

        }

        //Output.
        System.out.println(maxHourGlassValue);
    }
}

我只在评论中的代码中写了描述。如果有任何疑问,请参考并与我讨论。

相关问题