You are viewing a single comment's thread. Return to all comments →
Using a matrix template to make this far more readable (and reusable):
public class Solution { private static void prettyPrint(List<List<Integer>> arr, int xOffset, int yOffset, int size) { for (int x=0; x<size; x++) { for (int y=0; y<size; y++) { System.out.print(arr.get(x + xOffset).get(y + yOffset) + " "); } System.out.println(); } } private static int[][] hourglass = { {1, 1, 1}, {0, 1, 0}, {1, 1, 1} }; private static int sumHourglass(List<List<Integer>> arr, int xOffset, int yOffset) { int sum = 0; for (int x=0; x<3; x++) { for (int y=0; y<3; y++) { if (hourglass[x][y]==1) { sum += arr.get(x + xOffset).get(y + yOffset); } } } return sum; } public static void main(String[] args) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); List<List<Integer>> arr = new ArrayList<>(); final int n = 6; IntStream.range(0, n).forEach(i -> { try { arr.add( Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "").split(" ")) .map(Integer::parseInt) .collect(toList()) ); } catch (IOException ex) { throw new RuntimeException(ex); } }); bufferedReader.close(); int max = Integer.MIN_VALUE; for (int x=0; x<=n-3; x++) { for (int y=0; y<=n-3; y++) { // prettyPrint(arr, x, y, 3); final int sum = sumHourglass(arr, x, y); // System.out.println(sum); if (sum>max) max = sum; } } System.out.println(max); } }
Seems like cookies are disabled on this browser, please enable them to open this website
Java 2D Array
You are viewing a single comment's thread. Return to all comments →
Using a matrix template to make this far more readable (and reusable):