一张图像表示成NxN的矩阵,图像中每个像素是4个字节,写一个函数把图像旋转90度。 你能原地进行操作吗?(即不开辟额外的存储空间)

Cracking the coding interview--Q1.6

December 8, 2012
作者:Hawstein
出处: http://hawstein.com/posts/1.6.html
声明:本文采用以下协议进行授权:  自由转载-非商用-非衍生-保持署名|Creative Commons BY-NC-ND 3.0 ,转载请注明作者及出处。

题目

原文:

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?

译文:

一张图像表示成NxN的矩阵,图像中每个像素是4个字节,写一个函数把图像旋转90度。 你能原地进行操作吗?(即不开辟额外的存储空间)

解答

我们假设要将图像逆时针旋转90度,顺时针是一个道理。如果原图如下所示:

1 2 3 4 
5 6 7 8 
9 10 11 12 
13 14 15 16

那么逆时针旋转90度后的图应该是:

4 8 12 16 
3 7 11 15 
2 6 10 14 
1 5 9 13

我们要如何原地进行操作以达到上面的效果呢?可以分两步走。 第一步交换主对角线两侧的对称元素,第二步交换第i行和第n-1-i行,即得到结果。 看图示:

原图:           第一步操作后:   第二步操作后:
1 2 3 4         1 5 9 13        4 8 12 16
5 6 7 8         2 6 10 14       3 7 11 15
9 10 11 12      3 7 11 15       2 6 10 14
13 14 15 16     4 8 12 16       1 5 9 13

代码如下:

#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;
}

全书题解目录:

Cracking the coding interview—问题与解答

全书的C++代码托管在Github上:

https://github.com/Hawstein/cracking-the-coding-interview

 

将M*N的矩阵旋转90度

分类: 面试/笔试   88人阅读  评论(0)  收藏  举报

  请用最少的额外空间将一个M*N的矩阵旋转90度,写出算法描述和类c语言程序。(这是一道阿里巴巴的笔试编程题目)

  1. <span style="font-size:14px">#include <iostream>  
  2. using namespace std;  
  3. const int M = 5;  
  4. const int N = 3;  
  5.   
  6. int main()  
  7. {  
  8.   int a[M][N] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};  
  9.   int *p = a[0];  
  10.   
  11.   for(int i = 0;i < M;i++) // M = 5   
  12.   {  
  13.     for(int j = N-1;j >= 0;j--) // N = 3  
  14.     {  
  15.         cout << *(p + i + j*M) << ","// M = 5;  
  16.     }  
  17.     cout << endl;  
  18.   }    
  19.   return 0;  
  20. }</span>  

运行结果:



 我的思路是:每一次把矩阵为中心的每一圈旋转90度,把每一圈看做一个一维数组,循环移动

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值