像素反转 牛客网 程序员面试金典
题目描述
有一副由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]]
C++
class Transform { public: //run:17ms memory:740k vector<vector<int>> transformImage(vector<vector<int>> mat, int n){ int a; for(int i = 0; i < n/2; i++){ for(int j = 0; j < n; j++){ a = mat[i][j]; mat[i][j] = mat[n-i-1][j]; mat[n-i-1][j] = a; } } for(int i = 0; i < n; i++){ for(int j = 0; j < i; j++){ a = mat[i][j]; mat[i][j] = mat[j][i]; mat[j][i] = a; } } return mat; } };Python
class Transform: #run:263ms memory:5732k def transformImage(self, mat, n): a = None for i in range(n/2): for j in range(n): a = mat[i][j] mat[i][j] = mat[n-i-1][j] mat[n-i-1][j] = a for i in range(n): for j in range(i): a = mat[j][i] mat[j][i] = mat[i][j] mat[i][j] = a return mat
转载于:https://www.cnblogs.com/vercont/p/10210334.html
相关资源:JAVA上百实例源码以及开源项目