Vulkan

Cracking The Coding Interview 1.6

//原文:
//
//	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;
}

posted on 2014-04-03 09:45  Vulkan  阅读(145)  评论(0编辑  收藏  举报

导航