Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package Uprajnenie;
- import java.util.Scanner;
- public class MaximalSum {
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- // Read matrix dimensions
- int rows = scanner.nextInt();
- int cols = scanner.nextInt();
- scanner.nextLine(); // Consume newline
- // Read the matrix
- int[][] matrix = new int[rows][cols];
- for (int i = 0; i < rows; i++) {
- String[] rowValues = scanner.nextLine().split(" ");
- for (int j = 0; j < cols; j++) {
- matrix[i][j] = Integer.parseInt(rowValues[j]);
- }
- }
- // Find the square 3x3 with maximal sum
- int maxSum = Integer.MIN_VALUE;
- int startRow = 0;
- int startCol = 0;
- for (int i = 0; i <= rows - 3; i++) {
- for (int j = 0; j <= cols - 3; j++) {
- int currentSum = findSquareSum(matrix, i, j);
- if (currentSum > maxSum) {
- maxSum = currentSum;
- startRow = i;
- startCol = j;
- }
- }
- }
- // Print the square and its sum
- System.out.println("Sum = " + maxSum);
- for (int i = startRow; i < startRow + 3; i++) {
- for (int j = startCol; j < startCol + 3; j++) {
- System.out.print(matrix[i][j] + " ");
- }
- System.out.println();
- }
- }
- // Method to find the sum of a square 3x3
- private static int findSquareSum(int[][] matrix, int startRow, int startCol) {
- int sum = 0;
- for (int i = startRow; i < startRow + 3; i++) {
- for (int j = startCol; j < startCol + 3; j++) {
- sum += matrix[i][j];
- }
- }
- return sum;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement