• 【leetcode】Rotate Image(middle)


    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?

    思路:我的思路,先沿对角线对称,再左右对称。

    void rotate(int **matrix, int n) {
        //先沿对角线对称
        for(int i = 0; i < n; i++)
        {
            for(int j = 0; j < i; j++)
            {
                int tmp = matrix[i][j];
                matrix[i][j] = matrix[j][i];
                matrix[j][i] = tmp;
            }
        }
        //再左右对称
        for(int c = 0; c < (n + 1) / 2; c++)
        {
            for(int r = 0; r < n; r++)
            {
                int tmp = matrix[r][c];
                matrix[r][c] = matrix[r][n - c - 1];
                matrix[r][n - c - 1] = tmp;
            }
        }
        return;
    }

    大神一步到位的思路:找到每个圈要相互顺时针交换的4个位置,交换。

    class Solution {
    public:
        void rotate(vector<vector<int> > &matrix) {
            int n = matrix.size();
            if(n<=1) return;
            for(int i = 0; i!=n/2;i++) //行 圈数
            {
                for(int j = i;j!=n-1-i;j++)
                {
                swap(matrix[i][j],matrix[j][n-1-i]);
                swap(matrix[n-1-j][i],matrix[i][j]);
                swap(matrix[n-1-i][n-1-j],matrix[n-1-j][i]);
                }
            }
        }
        inline void swap(int &a,int &b)
        {
            a = b+a;
            b = a-b;
            a = a-b;
        }
    };
  • 相关阅读:
    微信小程序 模板语法-列表渲染
    Fast Matrix Calculation HDU
    AT4845 [ABC164E] Two Currencies
    [ABC127E] Cell Distance
    CF18E Flag 2
    CF10C Digital Root
    CF8C Looking for Order
    [ARC075B] Widespread
    旅行商问题
    AcWing 291. 蒙德里安的梦想
  • 原文地址:https://www.cnblogs.com/dplearning/p/4379431.html
Copyright © 2020-2023  润新知