Question

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.

Difficulty:Medium

Category:Array

Analyze

Solution

class Solution {
 public:
  void rotate(vector<vector<int>>& matrix) {
    const unsigned int n = matrix.size();

    // 1. 沿着对角线翻转一次
    for (int i = 0; i < n; ++i) {
      for (int j = 0; j < n - i; ++j) {
        swap(matrix[i][j], matrix[n - 1 - j][n - 1 - i]);
      }
    }

    // 2. 沿着水平中间线翻转一次
    for (int i = 0; i < n / 2; ++i) {
      for (int j = 0; j < n; ++j) {
        swap(matrix[i][j], matrix[n - 1 - i][j]);
      }
    }
  }
};
By guozetang            Updated: 2020-09-19 13:02:30

results matching ""

    No results matching ""