【Leetcode】Rotate Image

题目链接:https://leetcode.com/problems/rotate-image/

题目:

You are given an n x n 2D matrix representing an image.

Rotate the image by 90 degrees (clockwise).

Follow up:
Could you do this in-place?

思路:

先将矩阵转置,再将矩阵按中轴线对称交换每一列。

算法:

	public void rotate(int[][] matrix) {
		for (int i = 0; i < matrix.length; i++) { //转置
			for (int j = i; j < matrix[0].length; j++) {
				int tmp = matrix[i][j];
				matrix[i][j] = matrix[j][i];
				matrix[j][i] = tmp;
			}
		}
		for (int i = 0; i < matrix.length; i++) {//交换列
			for (int j = 0; j < matrix[0].length / 2; j++) {
				int tmp = matrix[i][j];
				matrix[i][j] = matrix[i][matrix[0].length - 1 - j];
				matrix[i][matrix[0].length - 1 - j] = tmp;
			}
		}
	}


你可能感兴趣的:(【Leetcode】Rotate Image)