给定一个N×N的二维矩阵表示图像,90度顺时针旋转图像。
样例
给出一个矩形[[1,2],[3,4]],90度顺时针旋转后,返回[[3,1],[4,2]]
挑战
能否在原地完成?
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Example
Given a matrix
[
[1,2],
[3,4]
]
rotate it by 90 degrees (clockwise), return
[
[3,1],
[4,2]
]
Challenge
Do it in-place.
思路:先以垂直线为中心水平翻转,再以逆对角线为中心斜向翻转。
public class Solution {
/**
* @param matrix: A list of lists of integers
* @return: Void
*/
public void rotate(int[][] matrix) {
if(null == matrix || matrix.length == 0 || matrix[0].length == 0) return;
int row = matrix.length;
int col = matrix[0].length;
if(row != col) return;
for(int i = 0; i < row; i++) {
for(int j = 0; j <= (col-1)/2; j++) {
int temp = matrix[i][j];
matrix[i][j] = matrix[i][col-1-j];
matrix[i][col-1-j] = temp;
}
}
for(int i = 0; i < row; i++) {
for(int j = 0; j < row-i-1; j++) {
int temp = matrix[i][j];
matrix[i][j] = matrix[row-j-1][row-i-1];
matrix[row-j-1][row-i-1] = temp;
}
}
}
}