diff --git a/docs/Leetcode_Solutions/C++/0048._Rotate_Image.md b/docs/Leetcode_Solutions/C++/0048._Rotate_Image.md new file mode 100644 index 0000000000000000000000000000000000000000..30feef74bb75e0c1fb9ead871b7fbaa626c7c95a --- /dev/null +++ b/docs/Leetcode_Solutions/C++/0048._Rotate_Image.md @@ -0,0 +1,71 @@ +# 49. Group Anagrams + + **难度: Medium** + + ## 刷题内容 + + > 原题连接 + +* https://leetcode.com/problems/rotate-image/submissions/ + + > 内容描述 + + ``` +给你一个矩阵,让你顺时针旋转90° 思路: 不讨论复制一个数组然后在旋转的方法,因为太简单了。 下面的方法都是in-place的:。 + +示例: + +输入: +[ + [1,2,3], + [4,5,6], + [7,8,9] +], + +输出: +[ + [7,4,1], + [8,5,2], + [9,6,3] +] +说明: + +必须直接修改输入的2D矩阵。 +不要分配另一个2D矩阵并进行旋转。 + ``` + +## 解题方案 +> 思路 1 +``` +直接设置top, bottom, left, right四个变量,表示圈定当前要旋转的正方形范围, +然后按偏移计算位置,比如左上角的先和右上角交换,然后继续左上角和右下角交换这样即可. +``` + +```cpp +class Solution { +public: + void rotate(vector>& matrix) { + if(matrix.empty()) + return; + int top = 0, bottom = matrix.size() - 1; + int left = 0, right = matrix[0].size() - 1; + for(;top < bottom && left < right; ++top, ++left, --bottom, --right){ + for(int i = left; i < right; ++i){ + int dis = i - left; + + int row = top + dis; + int col = right; + swap(matrix[top][i], matrix[row][col]); + + row = bottom; + col = right - dis; + swap(matrix[top][i], matrix[row][col]); + + row = bottom - dis; + col = left; + swap(matrix[top][i], matrix[row][col]); + } + } + } +}; +```