Leetcode 48 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  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

代码:

public class Solution {
    public void rotate(int[][] matrix) {		
        for(int i = 0; i < matrix.length; ++ i) {
        	for(int j = i; j < matrix[0].length; ++ j) {
        		int temp = matrix[i][j];
        		matrix[i][j] = matrix[j][i];
        		matrix[j][i] = temp;
        	}
        }
        for(int i = 0; i < matrix.length; ++i){
        	for (int j = 0; j < matrix[0].length / 2; ++ j) {
        		int temp = matrix[i][j];
        		matrix[i][j] = matrix[i][matrix[0].length-1-j];
        		matrix[i][matrix[0].length-1-j] = temp;
        	}
        }
    }
}


posted on 2017-05-10 10:33  lantx  阅读(105)  评论(0编辑  收藏  举报