leetcode解题之48. 旋转图像

问题
给定一个 n × n 的二维矩阵表示一个图像。
将图像顺时针旋转 90 度。

说明:
你必须在原地旋转图像,这意味着你需要直接修改输入的二维矩阵。请不要使用另一个矩阵来旋转图像。
示例 1:

给定 matrix =
[
[1,2,3],
[4,5,6],
[7,8,9]
],
原地旋转输入矩阵,使其变为:
[
[7,4,1],
[8,5,2],
[9,6,3]
]
示例 2:

给定 matrix =
[
[ 5, 1, 9,11],
[ 2, 4, 8,10],
[13, 3, 6, 7],
[15,14,12,16]
],

原地旋转输入矩阵,使其变为:
[
[15,13, 2, 5],
[14, 3, 4, 1],
[12, 6, 8, 9],
[16, 7,10,11]
]
思考
最初自己想到的是,横坐标与纵坐标的关系,但是最后。隐藏的规律复杂,但是其代码书写确是非常清晰简便。
先按照负对角线进行对角替换;之后在依照中间行进行一次转换。可以根据上面的示例进行下脑中演示。
你会惊讶的发现,竟然的确是有这个规律,额,这怎么会想到的,不顾怎么想到,把答案记录下来吧。

代码

package leetcode_01_50;

public class _48rotate {

	public void _48rotate(int[][] matrix) {

		rotatebymainline(matrix);
		rotatebyHline(matrix);
	}

	private void rotatebymainline(int[][] matrix) {
		// TODO Auto-generated method stub

		for (int i = 0; i < matrix.length; i++) {
			for (int j = 0; j < matrix.length - i - 1; j++) {
				int temp = matrix[i][j];
				matrix[i][j] = matrix[matrix.length - j - 1][matrix.length - i - 1];
				matrix[matrix.length - j - 1][matrix.length - i - 1] = temp;
			}
			// drawing a picture too lead u coding
		}

	}

	private void rotatebyHline(int[][] matrix) {
		// TODO Auto-generated method stub
		for (int i = 0; i < matrix.length / 2; i++) {
			for (int j = 0; j < matrix.length; j++) {
				int temp = matrix[i][j];
				matrix[i][j] = matrix[matrix.length - i - 1][j];
				matrix[matrix.length - i - 1][j] = temp;
			}
		}

	}

	public static void main(String[] args) {

		int[][] matrix = { { 5, 1, 9, 11 }, { 2, 4, 8, 10 }, { 13, 3, 6, 7 }, { 15, 14, 12, 16 } };

		_48rotate _48rotate = new _48rotate();
		_48rotate._48rotate(matrix);

	}
	// 看到的规律,x-y (n-x) 
	// y-x直接转换即可
	//但最后发现这个规律没有任何价值
}

猜你喜欢

转载自blog.csdn.net/xihuanyuye/article/details/100020686