[LeetCode]48. Rotate Image

  "把一个方阵旋转90度"

Posted by Stephen.Ri on February 27, 2018

Description

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

Rotate the image by 90 degrees (clockwise).

Note:

You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.

Example

Given input matrix =
[
[1,2,3],
[4,5,6],
[7,8,9]
],

rotate the input matrix in-place such that it becomes:
[
[7,4,1],
[8,5,2],
[9,6,3]
]

Discussion

给定一个方阵,代表了一张图片,要求把该图片顺时针旋转90度。

思路比较简单,如下图所示的1, 4, 16, 13四个数字作一组,2, 8, 15, 9四个数字作一组,依次类推,每组四个数字相互交换位置即可。

Rotate Image示意图

算法的时间复杂度为O(n^2)

C++ Code

class Solution {
public:
    void rotate(vector<vector<int>>& matrix) {
        int row, col;
        int n = matrix.size();
        col = n - 1;
        for(row = 0; row < n / 2; row ++) {
            for(col = row; col < n - 1 - row; col ++) {
                swap(matrix[row][col], matrix[col][n - 1 - row]);
                swap(matrix[row][col], matrix[n - 1 - row][n - 1 - col]);
                swap(matrix[row][col], matrix[n - 1 - col][row]);
            }
        }
    }
};