Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- namespace _02.MaxSubMatrix
- {
- class MaxSubMatrix
- {
- static void PrintSubMatrix(ref int[,] matrix, int bestRow, int bestCol, int size)
- {
- Console.WriteLine("The best submatrix with size {0} is", size);
- for (int i = 0; i < size; i++)
- {
- for (int k = 0; k < size; k++)
- {
- Console.Write("{0,4}", matrix[bestRow + i, bestCol + k]);
- }
- Console.WriteLine();
- }
- }
- static void PrintMatrix(int[,] matrix)
- {
- for (int row = 0; row < matrix.GetLength(0); row++)
- {
- for (int col = 0; col < matrix.GetLength(1); col++)
- {
- Console.Write("{0,4}",matrix[row,col]);
- }
- Console.WriteLine();
- }
- }
- static void Main(string[] args)
- {
- const int size = 3; // size of submatrix
- Console.Write("Enter N = ");
- int n = int.Parse(Console.ReadLine());
- Console.Write("Enter M = ");
- int m = int.Parse(Console.ReadLine());
- if (n<size||m<size)
- {
- Console.WriteLine("Wrong size of the matrix");
- return;
- }
- Console.WriteLine("The following random matrix is generated");
- int[,] matrix = new int[n, m];
- Random rand = new Random();
- for (int row = 0; row < matrix.GetLength(0); row++)
- {
- for (int col = 0; col < matrix.GetLength(1); col++)
- {
- matrix[row, col] = rand.Next(0, 21);
- }
- }
- PrintMatrix(matrix);
- int maxSum = int.MinValue;
- int currentSum = 0;
- int startElementRow = 0;
- int startElementCol = 0;
- for (int row = 0; row < matrix.GetLength(0)-size+1; row++)
- {
- for (int col = 0; col < matrix.GetLength(1)-size+1; col++)
- {
- for (int i = 0; i < size; i++)
- {
- for (int k = 0; k < size; k++)
- {
- currentSum += matrix[row + i, col + k];
- }
- }
- if (currentSum>maxSum)
- {
- maxSum = currentSum;
- startElementRow = row;
- startElementCol = col;
- }
- }
- }
- PrintSubMatrix(ref matrix, startElementRow, startElementCol, size);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement