как повернуть матрицу на 90 градусов
что я имею:
static void PutPixel(int x, int y, int codeColor)
{
ConsoleColor color = (ConsoleColor)codeColor;
Console.SetCursorPosition(x, y);
Console.ForegroundColor = color;
Console.Write("█");
}
static void DrawImageColor(int x, int y, int[,] image)
{
// по строчкам
for (int i = 0; i < image.GetLength(0); i++)
{
// по столбцам
for (int j = 0; j < image.GetLength(1); j++)
{
PutPixel(x + j, y + i, image[i, j]);
// Console.Write(image[i, j]);
}
}
}
static void Main(string[] args)
{
int[,] mas2 =
{
{00, 00, 00, 00, 00, 00, 00, 00, 00, 00},
{00, 10, 01, 10, 01, 10, 7, 00, 00, 00},
{00, 12, 00, 00, 00, 00, 10, 00, 00, 00},
{00, 10, 00, 00, 00, 00, 7, 00, 00, 00},
{00, 12, 00, 00, 00, 00, 10, 00, 00, 00},
{00, 10, 01, 01, 01, 01, 7, 00, 00, 00},
{00, 12, 00, 00, 00, 00, 10, 00, 00, 00},
{00, 10, 00, 00, 00, 00, 7, 00, 00, 00},
{00, 12, 00, 00, 00, 00, 10, 00, 00, 00},
{00, 10, 00, 00, 00, 00, 7, 00, 00, 00}
};
DrawImageColor(10, 10, mas2);
Console.ReadLine();
}
Ответы (2 шт):
Автор решения: tym32167
→ Ссылка
Меняем местами пиксели по кругу и все дела, пример для квадратной матрицы
public void Rotate(int[][] matrix)
{
var n = matrix.Length;
for (int i = 0; i < n / 2; i++)
{
var side = n - 2 * i - 1;
var row = i;
for (int j = 0; j < side; j++)
{
var col = i + j;
var v1 = matrix[row][col];
matrix[row][col] = matrix[n - 1 - col][row];
matrix[n - 1 - col][row] = matrix[n - 1 - row][n - 1 - col];
matrix[n - 1 - row][n - 1 - col] = matrix[col][n - 1 - row];
matrix[col][n - 1 - row] = v1;
}
}
}
Автор решения: aepot
→ Ссылка
Самый простой способ - это переписать элементы в новый массив. И работать будет для матриц любого размера, не только квадратных.
private static int[,] Rotate90(int[,] matrix)
{
int rows = matrix.GetLength(0);
int cols = matrix.GetLength(1);
int[,] result = new int[cols, rows];
for (int row = 0; row < rows; row++)
{
for (int col = 0; col < cols; col++)
{
result[col, rows - row - 1] = matrix[row, col];
}
}
return result;
}
mas2 = Rotate90(mas2); // 90 градусов по часовой стрелке
