题目
给定一个 n × n 的二维矩阵表示一个图像。
将图像顺时针旋转 90 度。
说明:
你必须在原地旋转图像,这意味着你需要直接修改输入的二维矩阵。请不要**使用另一个矩阵来旋转图像。
给定 matrix =
[
[1,2,3],
[4,5,6],
[7,8,9]
],
原地旋转输入矩阵,使其变为:
[
[7,4,1],
[8,5,2],
[9,6,3]
]
代码
class Program
{
static void Main(string[] args)
{
var a = new int[3][];
a[0] = new int[] { 1, 2, 3 };
a[1] = new int[] { 4, 5, 6 };
a[2] = new int[] { 7, 8, 9 };
Method(a);
Console.WriteLine("Hello World!");
}
private static void Method(int[][] matrix)
{
// 旋转矩阵
for (int i = 0; i < matrix.Length; i++)
{
int temp;
for (int j = i; j < matrix.Length; j++)
{
// 交换元素
temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
// 旋转每行元素
for (int i = 0; i < matrix.Length; i++)
{
/*
[
[1,2],
[3,4]
]
=>
[
[1,3],
[2,4]
]
*/
// 如果遍历的上限是 matrix.Length,则会将旋转后的元素复原了
int temp;
for (int j = 0; j < matrix.Length / 2; j++)
{
temp = matrix[i][j];
// 注意是 matrix.Length - j - 1
matrix[i][j] = matrix[i][matrix.Length - j - 1];
matrix[i][matrix.Length - j - 1] = temp;
}
}
}
}
注意两个边界条件:
- matrix.Length / 2
- matrix.Length - j - 1:元素对称性
网友评论