leetcode-48 Rotate Image 旋转矩阵

《程序员面试金典》P114 题目1.6
问题描述:
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?

问题分析:
题目要求旋转一个二维正方形数组矩阵90度,且空间复杂度为O(1)
leetcode-48 Rotate Image 旋转矩阵_第1张图片
程序需要做的就是一层一层进行遍历转换,

伪码:

for i = 0  :  n – 2 (注意此边界 n – 1 - 1)
    int temp = top[i];
    top[i]   = left[i];
    left[i]  = right[i];
    right[i] = temp;

假定top[i]对应的
行row = layer; 列 column = j;则:
Left: row = n – 1 – j; column = layer;
Bottom: row = n – 1 – layer; j = n – 1 – j;
Right: row = j; column = n – 1 – layer;

代码:

public class Solution {
    public void rotate(int[][] matrix) {
        int n = matrix.length;
        for (int layer = 0; layer < n / 2; layer ++) {
            // 注意旋转的边界,最后一个元素要注意留下来
            for (int j = layer; j < n - 1 - layer; j ++) {
                int temp = matrix[layer][j];
                matrix[layer][j] = matrix[n - 1 - j][layer];
                matrix[n - 1 - j][layer] = matrix[n - 1 - layer][n - 1 - j];
                matrix[n - 1 - layer][n - 1 - j] = matrix[j][n - 1 - layer];
                matrix[j][n - 1 - layer] = temp;
            }
        }
    }
}

你可能感兴趣的:(leetcode-48 Rotate Image 旋转矩阵)