1. 题目说明
有一副由NxN矩阵表示的图像,这里每个像素用一个int表示,请编写一个算法,在不占用额外内存空间的情况下(即不使用缓存矩阵),将图像顺时针旋转90度。
给定一个NxN的矩阵,和矩阵的阶数N,请返回旋转后的NxN矩阵,保证N小于等于500,图像元素小于等于256。
测试样例:
2. 解题思路
(1)一开始如果没有说明不能使用缓存矩阵的时候,大家应该都会想到直接new一个新的矩阵出来,然后遍历原矩阵在放在合适的位置即可。但有要求??没办法只能看第二种方法。
(2)其实细心的人可以发现只要把矩阵上下交换,再对角线交换即可。(可惜我不是一个细心的人。。。)
3. 代码实现
(1)
.。。。
(2)
import java.util.*;
public class Transform {
public int[][] transformImage(int[][] mat, int n) {
// write code here
if(mat == null)
return null;
int rows = mat.length;
int cols = mat[0].length;
//交换上下
for(int i = 0; i < rows/2; i++){
for(int j = 0; j < cols; j++){
int temp = mat[i][j];
mat[i][j] = mat[cols-i-1][j];
mat[cols-i-1][j] = temp;
}
}
//对角线交换i
for(int i = 0 ; i < cols ; i++){
for(int j = i ; j < cols ; j++){
int temp = mat[i][j];
mat[i][j] = mat[j][i];
mat[j][i] = temp;
}
}
return mat;
}
}