Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- class MatrixMaxSum
- {
- //Write a program that reads a rectangular matrix of size N x M and finds in it the square 3 x 3 that has maximal sum of its elements.
- static void Main()
- {
- // Input N and M
- Console.WriteLine("Enter N ");
- int rolCount = int.Parse(Console.ReadLine());
- Console.WriteLine("Enter M ");
- int colCount = int.Parse(Console.ReadLine());
- int maxRol = 0;
- int maxCol = 0;
- if (rolCount < 3 || colCount < 3)
- {
- Console.WriteLine("N >= 3 and M >=3");
- return; //Stop task
- }
- // Solution
- int[,] array = new int[rolCount, colCount];
- int sum = 0;
- int maxSum = 0;
- // Input elements of matrix
- Console.WriteLine("Enter elements ex. 1 3 4 ..");
- for (int i = 0; i < rolCount; i++)
- {
- string rolStr = Console.ReadLine(); // ex. 1 2 3
- string[] emptySpace = new string[] {" "}; // remove from split empty space
- string[] colStrArray = rolStr.Split(emptySpace, StringSplitOptions.RemoveEmptyEntries);
- for (int j = 0; j < colStrArray.Length; j++)
- {
- array[i, j] = int.Parse(colStrArray[j]); // Input digits in array
- }
- }
- for (int moveDown = 0; moveDown <= rolCount - 3; moveDown++)
- {
- for (int moveRight = 0; moveRight <= colCount - 3; moveRight++)
- {
- sum = 0;
- //Sumator
- for (int rol = moveDown; rol < 3 + moveDown; rol++)
- {
- for (int col = moveRight; col < 3 + moveRight; col++)
- {
- sum += array[rol, col];
- }
- }
- if (sum > maxSum)
- {
- maxSum = sum;
- maxRol = moveDown;
- maxCol = moveRight;
- }
- }
- }
- // Output
- Console.WriteLine("Max sum is : {0} ", maxSum);
- for (int i = maxRol; i < maxRol + 3; i++)
- {
- for (int j = maxCol; j < maxCol + 3; j++)
- {
- Console.Write(array[i,j]+" ");
- }
- Console.WriteLine();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement