CareerCup1.6

Question1.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?

从最外层到最里层逐层反转

顺时针的话:

int temp = mat[j][size-1-i];

mat[j][size-1-i]=mat[i][j];

mat[i][j]=mat[size-1-j][i];

mat[size-1-j][i]=mat[size-1-i][size-1-j];

mat[size-1-i][size-1-j]=temp;

逆时针相反


代码:

#include <iostream>
#include <fstream>
 
bool ReadFile(int**, int);
void Output(int**, int);
void Rotate(int**, int, int);
int main()
{
	using namespace std;
	cout<<"Enter the size please"<<endl;
	int size;
	cin>>size;
	//Construct the matrix
	if(size>0)
	{
		int **mat = new int*[size];
	
		for(int i=0;i<size;i++)
		{
			mat[i] = new int[size];
		}
		if(ReadFile(mat, size))
		{
			Rotate(mat,size,0);
			Output(mat,size);
		}
		//delete
		for(int i=0;i<size;i++)
		{
			delete[] mat[i];
		}
		delete[] mat;
	}
}
//Read Matrix from file
bool ReadFile(int **mat, int size)
{
	using namespace std;
	ifstream ifile;
	ifile.open("input.txt");
	if(!ifile)
	{
		cout<<"Open Unsuccess"<<endl;
		return false;
	}
	for(int i=0;i<size;i++)
	{
		for(int j=0;j<size;j++)
		{
			ifile>>mat[i][j];
		}
	}
	return true;
}
 
//Output the result through console
void Output(int **mat, int size)
{
	using namespace std;
	for(int i=0;i<size;i++)
	{
		for(int j=0;j<size;j++)
		{
			cout<<mat[i][j]<<" ";
		}
		cout<<endl;
	}
}
 
//Rotate the matrix, direction means clock-wise or not
void Rotate(int **mat, int size, int direction)
{
	using namespace std;
	for(int i=0;i<size/2;i++)
	{
		for(int j=i;j<size-i-1;j++)
		{
			switch(direction)
			{
				case 0:
				{
					int temp = mat[j][size-1-i];
					mat[j][size-1-i]=mat[i][j];
					mat[i][j]=mat[size-1-j][i];
					mat[size-1-j][i]=mat[size-1-i][size-1-j];
					mat[size-1-i][size-1-j]=temp;
					break;
				}
				case 1:
				{
					int temp = mat[i][j];
					mat[i][j]=mat[j][size-1-i];
					mat[j][size-1-i]=mat[size-1-i][size-1-j];
					mat[size-1-i][size-1-j]=mat[size-1-j][i];
					mat[size-1-j][i]=temp;
 
					break;
				}
				default:
				break;
			}
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值