Rotate Image
Q:
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?
A:
假设为n*n矩阵,则从外至内有n/2个圈需要旋转,每个圈旋转的时候是有固定的规律的,在纸上写一写应该就能发现,matrix[i][j] = matrix[n - j - 1][i],代码就很easy了。时间复杂度o(n^2),空间复杂度o(1),ok!
class Solution { public: void rotate(vector<vector<int> > &matrix) { // Start typing your C/C++ solution below // DO NOT write int main() function int len = matrix.size(); if (len <= 1) return; for (int i = 0; i < (len + 1)/2; ++i) { for (int j = i; j < len - i - 1; ++j) { int r = i; int c = j; int org = matrix[r][c]; for (int k = 0; k < 3; ++k) { matrix[r][c] = matrix[len - 1 - c][r]; int tmp = r; r = len - 1 - c; c = tmp; } matrix[r][c] = org; } } } };
Passion, patience, perseverance, keep it and move on.

浙公网安备 33010602011771号