Advertisement
emodev

Untitled

Jan 24th, 2019
712
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.96 KB | None | 0 0
  1. package LinearDataStructures.Exercises;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.IOException;
  5. import java.io.InputStreamReader;
  6.  
  7. public class e04_MaximalSum {
  8.     public static void main(String[] args) throws IOException {
  9.         BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
  10.  
  11.         int[][] matrix = fillMatrix(reader);
  12.  
  13.        int maxSum = Integer.MIN_VALUE;
  14.        int row = 0;
  15.        int col = 0;
  16.         for (int rows = 0; rows < matrix.length-2; rows++) {
  17.             for (int cols = 0; cols < matrix[0].length-2; cols++) {
  18.                 int sum = 0;
  19.                 sum += matrix[rows][cols] + matrix[rows][cols+1] + matrix[rows][cols+2];
  20.                 sum += matrix[rows+1][cols] + matrix[rows+1][cols+1] + matrix[rows+1][cols+2];
  21.                 sum += matrix[rows+2][cols] + matrix[rows+2][cols+1] + matrix[rows+2][cols+2];
  22.  
  23.                 if (sum > maxSum){
  24.                     maxSum = sum;
  25.                     row = rows;
  26.                     col = cols;
  27.                 }
  28.             }
  29.         }
  30.  
  31.  
  32.         System.out.println("Sum = " + maxSum);
  33.         for (int i = row; i < row+3; i++) {
  34.             for (int j = col; j < col+3; j++) {
  35.                 System.out.print(matrix[i][j] + " ");
  36.             }
  37.             System.out.println();
  38.         }
  39.  
  40.  
  41.  
  42.     }
  43.  
  44.      private static int[][] fillMatrix(BufferedReader reader) throws IOException {
  45.              String[] rowsCols = reader.readLine().split(" ");
  46.              int rows = Integer.parseInt(rowsCols[0]);
  47.              int cols = Integer.parseInt(rowsCols[1]);
  48.  
  49.              int[][] matrix = new int[rows][cols];
  50.              for (int row = 0; row < rows; row++) {
  51.                  String[] numsInput = reader.readLine().split(" ");
  52.                  for (int col = 0; col < cols; col++) {
  53.                      matrix[row][col] = Integer.parseInt(numsInput[col]);
  54.                  }
  55.              }
  56.              return matrix;
  57.  
  58.          }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement