Cracking The Coding Interview 1.6

来源:互联网 发布:淘宝宝贝如何排名靠前 编辑:程序博客网 时间:2024/05/22 01:54
//原文:////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?////先转置在上下交换#include <iostream>using namespace std;void swap(int &a, int &b){int t=a;a=b;b=t;}void replace(int **matrix, int size){for (int i = 0;i<size; i++){for (int j=i;j<size; j++){swap(matrix[i][j],matrix[j][i]);}}for (int i = 0; i<size/2; i++){for (int j=0;j<size; j++){swap(matrix[i][j],matrix[size-1-i][j]);}}}void display(int **matrix, int size){for (int k = 0; k<size; k++)for (int t = 0; t<size; t++){cout<<matrix[k][t];if (t==size-1){cout<<endl;}}}int main(){int size = 4;int **p = new int *[size];for (int i=0; i<size; i++){p[i] = new int[size];}for (int k = 0; k<size; k++)for (int t = 0; t<size; t++){p[k][t] = 2*k+t;}display(p,size);replace(p,size);cout<<endl;display(p,size);int a=3,b=4;swap(a,b);for (int k=0;k<size;k++){delete [] p[k];}delete p;return 0;}

0 0
原创粉丝点击