p48

LeetCode p48 Rotate Image 题解

1.题目:

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?

题意:

将一个矩阵顺时针转动90度。

2.解题思路:

先以对角线为轴心进行对调
例 :
1 2 3
4 5 6
7 8 9
变成:
1 4 7
2 5 8
3 6 9
再以垂直方向的中心线为轴心对调:
7 4 1
8 5 2
9 6 3
完成。细节见代码,注意边界条件。

3.代码


[title] [] [url] [link text]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
 
public class Solution {
public void rotate(int[][] matrix) {
int n = matrix.length;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
int c = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = c;
}
}

for (int j=0;j<n/2;j++)
{
for (int i=0;i<n;i++)
{
int c=matrix[i][j];
matrix[i][j]=matrix[i][n-1-j];
matrix[i][n-1-j]=c;
}
}

}
}


4.一些总结: