Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.ByteArrayInputStream;
- import java.util.Arrays;
- import java.util.Scanner;
- public class MatrixMaxSum {
- static void fakeInput() {
- String test = "6\n" +
- "1 2 3 4 5 6\n" +
- "2 3 4 5 6 7\n" +
- "6 5 4 3 2 1\n" +
- "3 4 5 6 7 8\n" +
- "4 5 6 7 8 9\n" +
- "9 8 7 6 5 4\n" +
- "3 5 3 -5 -4 -2";
- System.setIn(new ByteArrayInputStream(test.getBytes()));
- }
- public static void main(String[] args) {
- fakeInput();
- Scanner sc = new Scanner(System.in);
- int n = sc.nextInt();
- sc.nextLine();
- String[][] matrix = new String[n][];
- for (int row = 0; row < n; row++) {
- String[] line = sc.nextLine().split(" ");
- matrix[row] = line;
- }
- String[] coordinatesInput = sc.nextLine().trim().split(" ");
- int[] nextRow = new int[coordinatesInput.length / 2];
- int[] nextCol = new int[coordinatesInput.length / 2];
- int counter = 0;
- for (int index = 0; index < coordinatesInput.length; index += 2) {
- nextRow[counter] = Integer.parseInt(coordinatesInput[index]);
- nextCol[counter] = Integer.parseInt(coordinatesInput[index + 1]);
- counter++;
- }
- int cRow;
- int cCol;
- int tRow;
- int tCol;
- long maxSum = Long.MIN_VALUE;
- for (int index = 0; index < nextRow.length; index++) {
- tCol = Math.abs(nextCol[index]) - 1;
- long sum = 0;
- if (nextRow[index] >= 0) {
- cRow = nextRow[index] - 1;
- cCol = 0;
- } else {
- cRow = Math.abs(nextRow[index]) - 1;
- cCol = matrix[0].length - 1;
- }
- if (nextCol[index] >= 0) {
- tRow = 0;
- } else {
- tRow = matrix.length - 1;
- }
- while (cCol != tCol && cCol >= 0 && cCol < matrix[0].length) {
- sum += Integer.parseInt(matrix[cRow][cCol]);
- if (tCol > cCol) {
- cCol++;
- } else {
- cCol--;
- }
- if (cCol < 0 || cCol >= matrix.length) {
- break;
- }
- }
- while (cRow != tRow) {
- sum += Integer.parseInt(matrix[cRow][cCol]);
- if (tRow > cRow) {
- cRow++;
- } else {
- cRow--;
- }
- if (cRow < 0 || cRow >= matrix.length) {
- break;
- }
- }
- sum += Integer.parseInt(matrix[cRow][cCol]);
- if (sum > maxSum) {
- maxSum = sum;
- }
- // System.out.println(sum);
- }
- System.out.println(maxSum);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment