Skip to content

Latest commit

 

History

History
71 lines (56 loc) · 1.63 KB

0048._Rotate_Image.md

File metadata and controls

71 lines (56 loc) · 1.63 KB

49. Group Anagrams

难度: Medium

刷题内容

原题连接

内容描述

给你一个矩阵,让你顺时针旋转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四个变量,表示圈定当前要旋转的正方形范围,
然后按偏移计算位置,比如左上角的先和右上角交换,然后继续左上角和右下角交换这样即可.
class Solution {
public:
    void rotate(vector<vector<int>>& 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]);
            }
        }
    }
};