題目:
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?
題解:
這道題就是考察很直白的旋轉座標。要in place的。畫個圖自己算算就出來了。
程式碼如下:
1 /* public void rotate(int[][] matrix) {
2 int m = matrix.length;
3 int n = matrix[0].length;
4
5 int[][] result = new int[m][n];
6
7 for(int i = 0; i<m; i++){
8 for(int j = 0; j<n; j++){
9 result[j][m-1-i] = matrix[i][j];
10 }
11 }
12
13 for(int i=0;i<m;i++){
14 for(int j=0; j<n; j++){
15 matrix[i][j] = result[i][j];
16 }
17 }
18 }
19 */
20
21 //in place
22 public void rotate(int[][] matrix) {
23 int n = matrix.length;
24 for (int i = 0; i < n / 2; i++) {
25 for (int j = 0; j < Math.ceil(((double) n) / 2.); j++) {
26 int temp = matrix[i][j];
27 matrix[i][j] = matrix[n-1-j][i];
28 matrix[n-1-j][i] = matrix[n-1-i][n-1-j];
29 matrix[n-1-i][n-1-j] = matrix[j][n-1-i];
30 matrix[j][n-1-i] = temp;
31 }
32 }
2 int m = matrix.length;
3 int n = matrix[0].length;
4
5 int[][] result = new int[m][n];
6
7 for(int i = 0; i<m; i++){
8 for(int j = 0; j<n; j++){
9 result[j][m-1-i] = matrix[i][j];
10 }
11 }
12
13 for(int i=0;i<m;i++){
14 for(int j=0; j<n; j++){
15 matrix[i][j] = result[i][j];
16 }
17 }
18 }
19 */
20
21 //in place
22 public void rotate(int[][] matrix) {
23 int n = matrix.length;
24 for (int i = 0; i < n / 2; i++) {
25 for (int j = 0; j < Math.ceil(((double) n) / 2.); j++) {
26 int temp = matrix[i][j];
27 matrix[i][j] = matrix[n-1-j][i];
28 matrix[n-1-j][i] = matrix[n-1-i][n-1-j];
29 matrix[n-1-i][n-1-j] = matrix[j][n-1-i];
30 matrix[j][n-1-i] = temp;
31 }
32 }