Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- public class MaximalSum {
- public static void main(String[] args) {
- Scanner scan = new Scanner(System.in);
- String[] input = scan.nextLine().split("\\s+");
- int rows = Integer.parseInt(input[0]);
- int cols = Integer.parseInt(input[1]);
- int[][] matrix = new int[rows][cols];
- //Entering the matrix
- for (int i = 0; i < rows; i++) {
- String[] middle = scan.nextLine().split("\\s+");
- for (int j = 0; j < cols; j++) {
- matrix[i][j] = Integer.parseInt(middle[j]);
- }
- }
- //Count of matrices 3x3 in the big matrix
- int matrices = (rows - 2) * (cols - 2), counter = 0;
- int sum = 0;
- int maxSum = 0;
- int startI = 0, startJ = 0;
- while (counter<matrices) {
- //start and end indexes to go around all of the 3x3 matrices
- int endI = startI + 3;
- int endJ = startJ + 3;
- for (int i = startI; i < endI; i++) {
- for (int j = startJ; j < endJ; j++) {
- sum += matrix[i][j];
- }
- }
- if (sum > maxSum) {
- maxSum = sum;
- }
- sum = 0;
- counter++;
- if (endJ == cols) {
- startI++;
- startJ = 0;
- } else {
- startI = endI - 3;
- startJ ++;
- }
- }
- counter = 0;
- startI = 0;
- startJ = 0;
- sum = 0;
- System.out.println("Sum = " + maxSum);
- //Printing the 3x3 matrix with the max sum
- while (counter < matrices) {
- int endI = startI + 3;
- int endJ = startJ + 3;
- for (int i = startI; i < endI; i++) {
- for (int j = startJ; j < endJ; j++) {
- sum += matrix[i][j];
- }
- }
- if (sum == maxSum) {
- for (int i = startI; i < endI; i++) {
- for (int j = startJ; j < endJ; j++) {
- System.out.print(matrix[i][j] + " ");
- }
- System.out.println();
- }
- }
- sum = 0;
- counter++;
- if (endJ == cols) {
- startI++;
- startJ = 0;
- } else {
- startI = endI - 3;
- startJ ++;
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement