像素翻转

题目描述

有一副由NxN矩阵表示的图像,这里每个像素用一个int表示,请编写一个算法,在不占用额外内存空间的情况下(即不使用缓存矩阵),将图像顺时针旋转90度。

给定一个NxN的矩阵,和矩阵的阶数N,请返回旋转后的NxN矩阵,保证N小于等于500,图像元素小于等于256。

测试样例:
[[1,2,3],[4,5,6],[7,8,9]],3
返回:[[7,4,1],[8,5,2],[9,6,3]]

 1 import java.util.*;
 2 
 3 public class Transform {
 4     public int[][] transformImage(int[][] mat, int n) {
 5         // write code here
 6         for(int layer = 0 ;layer < n/2 ;++layer)
 7         {
 8             int first = layer;
 9             int last = n - 1 - layer;
10             for(int i = first ; i < last ;++i)//最后一个元素不用移动
11             {
12                 int offset = i - first;
13                 int top = mat[first][i];
14                 mat[first][i] = mat[last-offset][first];
15                 mat[last-offset][first] = mat[last][last-offset];
16                 mat[last][last-offset] = mat[i][last];
17                 mat[i][last] = top;
18             }
19         }
20         return mat;
21     }
22 }
原文地址:https://www.cnblogs.com/xiaoyesoso/p/5333455.html