CSharp · Console
using System;
using System.Collections.Generic;
public class E169
{
static readonly int[,] MATRIX = new int[,] {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
{10, 11, 12}
};
//static readonly int[,] MATRIX = new int[,] {
// {1, 2, 3, 4, 5, 6, 7, 8, 9, 0},
//{0, 9, 8, 7, 6, 5, 4, 3, 2, 1},
//{1, 3, 5, 7, 9, 2, 4, 6, 8, 0},
//{0, 8, 6, 4, 2, 9, 7, 5, 3, 1},
//{0, 1, 2, 3, 4, 5, 4, 3, 2, 1},
//{9, 8, 7, 6, 5, 6, 7, 8, 9, 0},
//{1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
//{2, 2, 2, 2, 2, 2, 2, 2, 2, 2},
//{9, 8, 7, 6, 7, 8, 9, 8, 7, 6},
//{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
//};
public static void Main(string[] args)
{
print(MATRIX);
Console.WriteLine();
int[,] rot90 = rotate(MATRIX);
print(rot90);
Console.WriteLine();
int[,] rot180 = rotate(rot90);
print(rot180);
Console.WriteLine();
int[,] rot270 = rotate(rot180);
print(rot270);
Console.WriteLine();
}
public static void print(int[,] matrix)
{
for(int i = 0; i < matrix.GetLength(0); ++i)
{
for(int j = 0; j < matrix.GetLength(1); ++j)
{
Console.Write("{0,3}", matrix[i, j]);
}
Console.WriteLine();
}
}
public static int[,] rotate(int[,] matrix)
{
return flipHorizontal(transpose(matrix));
}
public static int[,] transpose(int[,] matrix)
{
int R = matrix.GetLength(0);
int C = matrix.GetLength(1);
int[,] trans = new int[C, R];
for(int i = 0; i < R; ++i)
{
for(int j = 0; j < C; ++j)
{
trans[j, i] = matrix[i, j];
}
}
return trans;
}
public static int[,] flipHorizontal(int[,] matrix)
{
int R = matrix.GetLength(0);
int C = matrix.GetLength(1);
int R2 = (R >> 1);
int[,] flipped = new int[R, C];
for(int i = 0; i < R2; ++i)
{
Array.Copy(matrix, i * C, flipped, (R - i - 1) * C, C);
Array.Copy(matrix, (R - i - 1) * C, flipped, i * C, C);
}
if ((R & 1) == 1)
Array.Copy(matrix, R2 * C, flipped, R2 * C, C);
return flipped;
}
}