LeetCode Online Judge 题目C# 练习 - Rotate Image

You are given an n x n 2D matrix representing an image.

Rotate the image by 90 degrees (clockwise).

Follow up:

Could you do this in-place?

 1         public static void RotateImage(List<List<int>> matrix)
 2         {
 3             if (matrix.Count <= 1)
 4                 return;
 5 
 6             int n = matrix.Count - 1;
 7 
 8             Debug.Assert(n == matrix[0].Count);
 9 
10             int temp;
11             for (int i = 0; i <= n / 2; i++)
12             {
13                 for (int j = i; j < n - i; j++)
14                 {
15                     temp = matrix[i][j];
16                     matrix[i][j] = matrix[n - j][i];
17                     matrix[n - j][i] = matrix[n - i][n - j];
18                     matrix[n - i][n - j] = matrix[j][n - i];
19                     matrix[j][n - i] = temp;
20                 }
21             }
22         }

代码分析:

  没什么好说的,i 是 每次开始的位置,(0,0),(1,1),(2,2)...... j 就是迭代每一行,每一列的元素。