Advertisement
Ligh7_of_H3av3n

05. Maximum Sum of 2x2 Submatrix

May 16th, 2024
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.01 KB | None | 0 0
  1. package Lekciq;
  2.  
  3. import java.util.Scanner;
  4.  
  5. public class MaximumSumOfTwoByTwoSubmatrix {
  6.     public static void main(String[] args) {
  7.         Scanner scanner = new Scanner(System.in);
  8.  
  9.  
  10.         // Read matrix dimensions
  11.         String[] dimensions = scanner.nextLine().split(", ");
  12.         int rows = Integer.parseInt(dimensions[0]);
  13.         int columns = Integer.parseInt(dimensions[1]);
  14.  
  15.         // Initialize the matrix
  16.         int[][] matrix = new int[rows][columns];
  17.  
  18.         // Read matrix elements
  19.         for (int i = 0; i < rows; i++) {
  20.             String[] rowElements = scanner.nextLine().split(", ");
  21.             for (int j = 0; j < columns; j++) {
  22.                 matrix[i][j] = Integer.parseInt(rowElements[j]);
  23.             }
  24.         }
  25.  
  26.         // Find the biggest sum of a 2x2 submatrix
  27.         int maxSum = Integer.MIN_VALUE;
  28.         int[][] maxSubmatrix = new int[2][2];
  29.  
  30.         for (int i = 0; i < rows - 1; i++) {
  31.             for (int j = 0; j < columns - 1; j++) {
  32.                 int currentSum = matrix[i][j] + matrix[i][j + 1] +
  33.                         matrix[i + 1][j] + matrix[i + 1][j + 1];
  34.  
  35.                 if (currentSum > maxSum) {
  36.                     maxSum = currentSum;
  37.                     maxSubmatrix[0][0] = matrix[i][j];
  38.                     maxSubmatrix[0][1] = matrix[i][j + 1];
  39.                     maxSubmatrix[1][0] = matrix[i + 1][j];
  40.                     maxSubmatrix[1][1] = matrix[i + 1][j + 1];
  41.                 }
  42.             }
  43.         }
  44.  
  45.         // Print the submatrix and its sum
  46.         printMatrix(maxSubmatrix);
  47.         System.out.println(maxSum);
  48.     }
  49.  
  50.     // Method to print a matrix
  51.     private static void printMatrix(int[][] matrix) {
  52.         for (int[] ints : matrix) {
  53.             for (int j = 0; j < matrix[0].length; j++) {
  54.                 System.out.print(ints[j]);
  55.                 if (j < matrix[0].length - 1) {
  56.                     System.out.print(" ");
  57.                 }
  58.             }
  59.             System.out.println();
  60.         }
  61.     }
  62. }
  63.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement