Путем перестановки строк и столбцов матрицы сделать так, чтобы максимальный элемент был в верхнем левом углу - C#
Формулировка задачи:
Матрица, размеры вводятся с клавиатуры. Заполнение рандомом. Путем перестановки строк и столбцов сделать так, чтобы максимальный элемент был в верхнем левом углу.
Решение задачи: «Путем перестановки строк и столбцов матрицы сделать так, чтобы максимальный элемент был в верхнем левом углу»
textual
Листинг программы
using System;
namespace Sort2DimArray
{
class Program
{
static void Main(string[] args)
{
int r, c;
do
{
Console.Write("Количество столбцов: ");
} while (!int.TryParse(Console.ReadLine(), out c));
do
{
Console.Write("Количество строк: ");
} while (!int.TryParse(Console.ReadLine(), out r));
int[,] matrix = new int[r, c];
//Заполнение матрицы
Random rnd = new Random();
for (int i = 0; i <= matrix.GetUpperBound(0); i++)
for (int j = 0; j <= matrix.GetUpperBound(1); j++)
matrix[i, j] = rnd.Next(1, (matrix.GetUpperBound(0) + 1) * (matrix.GetUpperBound(1) + 1));
//Поиск максимального элемента
int imax = 0, jmax = 0, max = matrix[0, 0];
for (int i = 0; i <= matrix.GetUpperBound(0); i++)
{
for (int j = 0; j <= matrix.GetUpperBound(1); j++)
if (matrix[i, j] > max)
{
max = matrix[i, j];
imax = i;
jmax = j;
}
}
Console.WriteLine("Максимальный элемент: {0}\r\nСтолбец: {1}\r\nСтрока: {2}\r\n", max, jmax + 1, imax + 1);
PrintMatrix("Исходная матрица", matrix, imax, jmax);
int temp = 0;
//Меняем столбцы местами
for (int i = 0; i <= matrix.GetUpperBound(0); i++)
{
temp = matrix[i, 0];
matrix[i, 0] = matrix[i, jmax];
matrix[i, jmax] = temp;
}
//Меняем строки местами
for (int j = 0; j <= matrix.GetUpperBound(1); j++)
{
temp = matrix[0, j];
matrix[0, j] = matrix[imax, j];
matrix[imax, j] = temp;
}
PrintMatrix("Отсортированная матрица", matrix, 0, 0);
Console.ReadLine();
}
//Вывод матрицы в консоль. Строка и столбец с максимальным элементом выделяются цветом
static void PrintMatrix(string header,int[,] matrix, int row, int col)
{
Console.WriteLine("\r\n=====================================");
Console.WriteLine(header);
Console.WriteLine("=====================================\r\n");
for (int i = 0; i <= matrix.GetUpperBound(0); i++)
{
for (int j = 0; j <= matrix.GetUpperBound(1); j++)
{
if (col != -1 && col == j || row != -1 && i == row)
{
Console.BackgroundColor = ConsoleColor.Yellow;
Console.ForegroundColor = ConsoleColor.Black;
}
Console.Write(matrix[i, j].ToString());
Console.ResetColor();
Console.Write("\t");
}
Console.WriteLine("\r\n");
}
}
}
}