【CareerCup】 Arrays and Strings—Q1.5

來源:互聯網
上載者:User

轉載請註明出處:http://blog.csdn.net/ns_code/article/details/21478019


    題目:

    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度。要求旋轉操作儘可能原地操作(即不開闢額外的儲存空間)。

    思路:

    我們這裡以逆時針旋轉為例(寫代碼時比較容易理解,順時針旋轉的實現思想相似),可以先將原矩陣以主對角線為對稱軸,交換主對角線兩側的的元素,得到新的矩陣(如果是順時針旋轉,可以交換副對角線兩側的元素),再將該矩陣的第i行和第n-i-i行相交換,即得到逆時針旋轉後的矩陣。

    實現代碼:

/*******************************************************題目描述:將n*n的矩陣原地(即不開闢額外的輔助空間)逆時針旋轉90度Date:2014-03-18********************************************************/#define N 4#include<stdio.h>void swap(int *a,int *b){*a = *a + *b;*b = *a - *b;*a = *a - *b;}void rotate(int A[][N],int n){int i,j;for(i=0;i<n;i++)for(j=i+1;j<n;j++)swap(&A[i][j],&A[j][i]);for(i=0;i<n/2;i++)for(j=0;j<n;j++)swap(&A[i][j],&A[n-i-1][j]);}int main(){int A[N][N] = {{11,12,13,14},{15,16,17,18},{19,20,21,22},{23,24,25,26}};int i,j;printf("the orginal matrix:\n");for(i=0;i<N;i++){for(j=0;j<N;j++)printf("%d ",A[i][j]);printf("\n");}rotate(A,N);printf("the rotated matrix:\n");for(i=0;i<N;i++){for(j=0;j<N;j++)printf("%d ",A[i][j]);printf("\n");}return 0;}

    測試結果:



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.