Implementation:
static void ReverseMatrix<T>(T[,] matrix)
{
int width = matrix.GetLength(1);
int height = matrix.GetLength(0);
int startRow = 0;
int startCol = 0;
int endRow = height-1;
int endCol = width-1;
while (true)
{
if (startRow == height-1 || endRow == 0) return;
// swap
var temp = matrix[startRow, startCol];
matrix[startRow, startCol] = matrix[endRow, endCol];
matrix[endRow, endCol] = temp;
startCol++;
endCol--;
if (startCol == width)
{
startRow++;
startCol = width - 1;
}
if (endCol == -1)
{
endRow--;
endCol = 0;
}
}
}
Test program:
static void Main()
{
var matrix = new[,]
{
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
ReverseMatrix(matrix);
PrintMatrix(matrix);
}
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}\t",matrix[row,col]);
}
Console.WriteLine();
}
}
Input:
1 2 3 4 5 6 7 8 9
Output:
9 8 7 6 5 4 3 2 1
How can I improve this implementation?