给定一幅NXN矩阵表示的图像,其中每个像素的大小为4字节,编写一个方法,将图像旋转90度。不占用额外内存空间能否做到?
分析:此处假设对图像做顺时针旋转。对于image[i][j],其顺时针旋转角度与对应点坐标分别为:90度--image[j][n-i-1], 180度--image[n-i][n-j], 270度--image[n-j][i]。赋值流程为:tmp <-- image[i][j] <-- image[n-i-1][j] <-- image[n-i-1][n-j-1] <-- image[i][n-j-1] <-- tmp。
1 #include2 #include 3 #include 4 #include 5 #include 6 7 using namespace std; 8 9 void rotate( vector >& image );10 11 int main( int argc, char *argv[] ) {12 string data_file = "./1.6.txt";13 ifstream ifile( data_file.c_str(), ios::in );14 if( !ifile.is_open() ) {15 fprintf( stderr, "cannot open file: %s\n", data_file.c_str() );16 return -1;17 }18 int n = 0;19 while( ifile >>n ) {20 vector > image( n, vector ( n, 0 ) );21 assert( n > 0 );22 cout <<"input:" < >image[i][j];26 cout < <<" ";27 }28 cout < >& image ) {45 int n = image.size();46 if( --n <= 0 ) { return; }47 for( int i = 0; i <= n/2; ++i ) {48 for( int j = i; j < n-i; ++j ) {49 unsigned int tmp = image[i][j];50 image[i][j] = image[n-j][i];51 image[n-j][i] = image[n-i][n-j];52 image[n-i][n-j] = image[j][n-i];53 image[j][n-i] = tmp;54 }55 }56 return;57 }
测试文件
1121 23 431 2 34 5 67 8 941 2 3 44 5 6 79 10 11 1213 14 15 165232 123 243 231 211654 123 123 134 876142 562 475 987 321235 635 478 693 146111 222 323 454 656