题目:
Given an image represented by an NxN matrix, where each pixel in the image is 4 bytes
write a method to rotate the image by 90 degrees. Can you do this in place?
解决思想:
顺时针:先将矩阵转置 再将依次将各行首尾互换
逆时针:先将矩阵转置 再将依次将各列首尾互换
以4X4矩阵逆时针旋转90°为例:
#include <iostream> using namespace std; void swap(int &a, int &b){ int t = a; a = b; b = t; } void transpose(int a[][4], int n){ for(int i=0; i<n; ++i) for(int j=i+1; j<n; ++j) swap(a[i][j], a[j][i]); for(int i=0; i<n/2; ++i) for(int j=0; j<n; ++j) swap(a[i][j], a[n-1-i][j]); } int main(){ int a[4][4] = { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16} }; for(int i=0; i<4; ++i){ for(int j=0; j<4; ++j) cout<<a[i][j]<<" "; cout<<endl; } cout<<endl; transpose(a, 4); for(int i=0; i<4; ++i){ for(int j=0; j<4; ++j) cout<<a[i][j]<<" "; cout<<endl; } return 0; }
原文:http://blog.csdn.net/smileteo/article/details/21202431