zoukankan      html  css  js  c++  java
  • 数组与字符串 1.6

    给定一幅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 #include <iostream>
     2 #include <fstream>
     3 #include <cstring>
     4 #include <vector>
     5 #include <assert.h>
     6 
     7 using namespace std;
     8 
     9 void rotate( vector<vector<unsigned int> >& 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
    ", data_file.c_str() );
    16         return -1;
    17     }
    18     int n = 0;
    19     while( ifile >>n ) {
    20         vector<vector<unsigned int> > image( n, vector<unsigned int>( n, 0 ) );
    21         assert( n > 0 );
    22         cout <<"input:" <<endl;
    23         for( int i = 0; i < n; ++i ) {
    24             for( int j = 0; j < n; ++j ) {
    25                 ifile >>image[i][j];
    26                 cout <<image[i][j] <<" ";
    27             }
    28             cout <<endl;
    29         }
    30         rotate( image );
    31         cout <<"result:" <<endl;
    32         for( int i = 0; i < n; ++i ) {
    33             for( int j = 0; j < n; ++j ) {
    34                 cout <<image[i][j] <<" ";
    35             }
    36             cout <<endl;
    37         }
    38         cout <<endl;
    39     }
    40     ifile.close();
    41     return 0;
    42 }
    43 
    44 void rotate( vector<vector<unsigned int> >& 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 }

    测试文件

    1
    1
    
    2
    1 2
    3 4
    
    3
    1 2 3
    4 5 6
    7 8 9
    
    4
    1 2 3 4
    4 5 6 7
    9 10 11 12
    13 14 15 16
    
    5
    232 123 243 231 211
    654 123 123 134 876
    142 562 475 987 321
    235 635 478 693 146
    111 222 323 454 656
  • 相关阅读:
    Server.UrlEncode UrlDecode 动态绑定gridview列发送接收乱码的问题
    gridview新用法,一直不知道gridview可以这么用
    vm workstation15 迁移至ESXi6.7步骤
    http 502与504的区别
    Asp.net项目部署ActiveReport
    不能在 Page 回调中调用 Response.Redirect 解决方法
    JQuery TextExt 控件使用
    通过ashx获取JSON数据的两种方式
    jQuery Mobile对话框插件
    替换文本框title提示文本
  • 原文地址:https://www.cnblogs.com/moderate-fish/p/3971557.html
Copyright © 2011-2022 走看看