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?
思路:将这个矩阵沿左对角线(从左上角到右下角)对称变换,再进行左右对称变换。
1 class Solution { 2 public: 3 void rotate(vector<vector<int>>& matrix) { 4 for (int i = 0, n = matrix.size(); i < n; i++) 5 for (int j = i + 1; j < n; j++) 6 swap(matrix[i][j], matrix[j][i]); 7 for (int i = 0, n = matrix.size(); i < n; i++) 8 for (int j = (n - 1) / 2 + 1; j < n; j++) 9 swap(matrix[i][j], matrix[i][n - j - 1]); 10 } 11 };
本文介绍了一个高效的算法,用于实现二维矩阵的90度顺时针旋转,并提供了具体的C++实现代码。该算法通过两次对称变换实现了原地(in-place)旋转,首先沿左对角线对称变换,然后进行左右对称变换。
240

被折叠的 条评论
为什么被折叠?



