borko9696

Problem 2. Maximal Sum

Sep 21st, 2015
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.24 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. class MaximalSum
  8. {
  9.     static void Main()
  10.     {
  11.        
  12.         int[] sides = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
  13.         int[,] matrix = new int[sides[0], sides[1]];
  14.        
  15.  
  16.         for (int row = 0; row < sides[0]; row++)
  17.         {
  18.  
  19.             string str = Console.ReadLine();
  20.             string[] elements = str.Split(' ');
  21.  
  22.             for (int col = 0; col < sides[1]; col++)
  23.             {
  24.                 matrix[row, col] = int.Parse(elements[col]);
  25.             }
  26.         }
  27.         int bestSum = int.MinValue;
  28.         List<int> bestMatrixNumbers = new List<int>();
  29.         int counterRow = 0;
  30.         int counterCol = 0;
  31.  
  32.         for (int row = 0; row < matrix.GetLength(0)-2; row++)
  33.         {
  34.             for (int col = 0; col <matrix.GetLength(1)-2; col++)
  35.             {
  36.                 int sum =
  37.                     matrix[row, col] + matrix[row, col + 1] + matrix[row, col + 2] +
  38.                     matrix[row + 1, col] + matrix[row + 1, col + 1] + matrix[row + 1, col + 2] +
  39.                     matrix[row + 2, col] + matrix[row + 2, col + 1] + matrix[row + 2, col + 2];
  40.                
  41.                 if (sum>bestSum)
  42.                 {
  43.                    
  44.                     bestSum = sum;
  45.                     bestMatrixNumbers.Clear();
  46.  
  47.                     for (int i = 0; i < 3; i++)
  48.                     {
  49.                        
  50.                         for (int j = 0; j < 3; j++)
  51.                         {
  52.                             bestMatrixNumbers.Add(matrix[i+counterRow, j+counterCol]);
  53.                            
  54.                         }
  55.                      
  56.                     }
  57.                 }
  58.  
  59.             }
  60.             counterCol++;
  61.             counterRow++;
  62.         }
  63.  
  64.         Console.WriteLine("Sum= {0}",bestSum);
  65.  
  66.         int counter=0;
  67.  
  68.         while (counter < 9)
  69.         {
  70.             Console.Write("{0} ", bestMatrixNumbers[counter]);
  71.             if (counter == 2 || counter == 5 || counter == 8)
  72.             {
  73.                 Console.WriteLine();
  74.             }
  75.             counter++;
  76.         }
  77.        
  78.        
  79.     }
  80. }
Advertisement
Add Comment
Please, Sign In to add comment