Arrays_Strings 90度顺时针逆时针旋转方形矩阵 @CareerCup

原文:

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度。 你能原地进行操作吗?(即不开辟额外的存储空间)


关键是in place旋转,不能另开空间

两种做法:

1 通用做法如下图:用swap的方法,把黄->绿,绿->蓝,蓝->红,红->黄

又注意到黄的部分:总是在first行,只是列在变,所以可以表示成 M[first][i]

绿的部分:总在last列,只是行在变,所以M[i][last]

蓝的部分:总在last行,只是列在变,所以M[last][last-offset]

红的部分:总在first列,只是行在变,所以M[last-offset][first]

offset是表示当前元素i到first元素的距离,用来和last搭配使用


first i last

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16




2 一种捷径如果是逆时针旋转则可以第一步交换主对角线两侧的对称元素,第二步交换第i行和第n-1-i行,即得到结果。

顺时针同理。具体参考:http://hawstein.com/posts/1.6.html 但我觉得不如第一种有普遍性。


Followup:

这道题关键是矩阵是一个方形矩阵,所以能in place旋转。但如果是一个M*N的矩阵,则该怎么做?

可参考LeetCode上有一道题:Spiral Matrix I II



package Arrays_Strings;

import CtCILibrary.AssortedMethods;

public class S1_6 {

	// 顺时针90度旋转矩阵
	public static void rotateClockwise(int[][] M, int n) {
		for(int layer=0; layer<n/2; layer++) {			// 层
			int first = layer;						// 要处理的第一个元素
			int last = n - 1 - layer;				// 最后一个元素,不用处理
			for(int i=first; i<last; i++){
				int offset = i - first;				// offset: 当前处理元素和第一个元素之间之差,用于last元素向前
				int top = M[first][i];									// Save top
				M[first][i] = M[last-offset][first];				// left -> top 
				M[last-offset][first] = M[last][last-offset];	// bottom -> left
				M[last][last-offset] = M[i][last];					// right -> bottom
				M[i][last] = top;										// top->right
			}
		}
	}

	// 逆时针90度旋转矩阵
	public static void rotateAntiClockwise(int[][] M, int n) {
		for(int layer=0; layer<n/2; layer++) {
			int first = layer;
			int last = n - 1 - layer;
			for(int i=first; i<last; i++){
				int offset = i - first;
				int top = M[first][i];									// Save top
				M[first][i] = M[i][last];								// right -> top 
				M[i][last] = M[last][last-offset];					// bottom -> right
				M[last][last-offset] = M[last-offset][first];	// left -> bottom
				M[last-offset][first] = top;							// top->left
			}
		}
	}
	
	
	public static void main(String[] args) {
		int[][] matrix = AssortedMethods.randomMatrix(5, 5, 0, 9);
		AssortedMethods.printMatrix(matrix);
		rotateClockwise(matrix, 5);
		System.out.println();
		AssortedMethods.printMatrix(matrix);
		rotateAntiClockwise(matrix, 5);
		System.out.println();
		AssortedMethods.printMatrix(matrix);
	}
	
	

}






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值