Leetcode C++《热题 Hot 100-34》48.旋转图像

Leetcode C++《热题 Hot 100-34》48.旋转图像

  1. 题目

给定一个 n × n 的二维矩阵表示一个图像。

将图像顺时针旋转 90 度。

说明:

你必须在原地旋转图像,这意味着你需要直接修改输入的二维矩阵。请不要使用另一个矩阵来旋转图像。

示例 1:

给定 matrix =
[
[1,2,3],
[4,5,6],
[7,8,9]
],

原地旋转输入矩阵,使其变为:
[
[7,4,1],
[8,5,2],
[9,6,3]
]

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/rotate-image
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

  1. 思路
  • 方案1:转置翻转(上下翻转,对角线翻转),通俗易懂
  • 方案2:直接计算出每一个位置的index坐标;参考一个写的蛮好的题解:https://leetcode-cn.com/problems/rotate-image/solution/o1-kong-jian-you-wai-dao-nei-yi-ci-yi-dong-by-amir/
    • 时间复杂度是o(n*n),空间复杂度是o(1)
  1. 代码
class Solution {
public:
    //今晚11点半必须睡觉,这个题感觉有个思路就可以,没啥技术含量
    //最容易理解的,方案1:先上下翻转,再对角线翻转 (太巧妙了)
    // n * n 矩阵大小
    /*void rotate(vector<vector<int>>& matrix) {    
        int n = matrix.size();
        for (int i = 0; i < n/2; i++)
            swap(matrix[i], matrix[n-1-i]);
        for (int i = 0; i < n; i++) {
            for (int j = i; j < n; j++) {
                swap(matrix[i][j], matrix[j][i]); 
            }
        }
    }*/

    //方案2:必须学习一下,直接计算出每一个位置的index坐标
    //参考一个写的蛮好的题解:https://leetcode-cn.com/problems/rotate-image/solution/o1-kong-jian-you-wai-dao-nei-yi-ci-yi-dong-by-amir/
    void rotate(vector<vector<int>>& matrix) {
        int n = matrix.size();
        for (int j = 0; j < n/2; j++) {
            int length = n - j*2;
            for (int i = j; i < j+length-1; i++) {
                int x = j; 
                int y = i;
                int beforeV = matrix[x][y];
                //cout << x << " " << y << endl;
                for (int k = 0 ; k < 4; k++) {
                    int newX;
                    int newY;
                    nextPos(x,y,n,newX, newY);
                    //cout << newX << " " << newY  << " " << beforeV << endl;
                    int temp = matrix[newX][newY];
                    matrix[newX][newY] = beforeV;
                    beforeV = temp;
                    x= newX;
                    y = newY;
                }
            }
            //break;

        }
    }

    void nextPos(int x , int y, int length, int& newX, int& newY) {
        newY = length-1-x; //length的长度是矩阵的长度
        newX = y; //怎么找这个对应关系,做两轮循环【对角线循环,则x+y=固定值】
    }


};
发布了205 篇原创文章 · 获赞 8 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/Alexia23/article/details/104196709
今日推荐