现在的位置: 首页 > 综合 > 正文

1.6

2013年08月09日 ⁄ 综合 ⁄ 共 842字 ⁄ 字号 评论关闭

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?

分析:4个bytes告诉我们可以用整型来表示每个元素,关键是旋转的过程。这道题目一开始我就理解错了,感觉像素的旋转不应该这么简单。但是,即使这样旋转的话,我也没有什么好的思路。参考了答案:

a、b、c分别替换了A、B、C。

我们使用层来进行旋转操作,总共需要旋转0~(n/2-1)层

void rotate(int **matrix, int n){
	if(matrix==NULL||n<=0) return;
	for(int layer=0;layer<n/2;layer++){
		int first=layer;
		int last=n-layer-1;//从右边减去层数
		for(int i=first;i<last;i++){
			int sum=first+last;//因为旋转对应元素的行和列的和为first+last
			int tmp=matrix[first][i];
			//left->top
			matrix[first][i]=matrix[sum-i][first]; 
			//bottom->left
			matrix[sum-i][first]=matrix[last][sum-i];
			//right->bottom
			matrix[last][sum-i]=matrix[i][last];
			//top->right
			matrix[i][last]=tmp; 
		} 
	}
}

注:当将参数写成char matrix[][]的时候会错误!

原因:因为从实参传递来的是数组的起始地址,在内存中按数组排列规则存放(按行存放),而并不区分行和列,如果在形参中不说明列数,则系统无法决定应为多少行多 少列,不能只指定一维而不指定第二维,void
Func(int array[3][])这种也是错误的。

抱歉!评论已关闭.