Leetcode95: Rotate Image

来源:互联网 发布:c语言二维数组初始化 编辑:程序博客网 时间:2024/04/29 14:00

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?

举一个二维数组变换的例子就知道变换的坐标由a[i][j]->a[j][n-1-i]

最笨的办法就是复制数组然后再重新赋值

class Solution {public:    void rotate(vector<vector<int>>& matrix) {        int n = matrix.size();        vector<vector<int> > tmp(n, vector<int>(n));        for(int i = 0; i < n; i++)        {            for(int j = 0; j < n; j++)            {                tmp[i][j] = matrix[i][j];            }        }                for(int i = 0; i < n; i++)        {            for(int j = 0; j < n; j++)            {                matrix[j][n-1-i] = tmp[i][j];            }        }    }};
然后在网上看到一个技巧,把数组先沿着中间一行上下对调,然后沿着对角线对调即可,不用开辟新的空间存储。

class Solution {public:    void rotate(vector<vector<int>>& matrix) {        int n = matrix.size();        int tmp;        for(int i = 0; i < n/2; i++)        {            for(int j = 0; j < n; j++)            {                tmp = matrix[i][j];                matrix[i][j] = matrix[n-1-i][j];                matrix[n-1-i][j] = tmp;            }        }                for(int i = 0; i < n; i++)        {            for(int j = 0; j < i; j++)            {                tmp = matrix[i][j];                matrix[i][j] = matrix[j][i];                matrix[j][i] = tmp;            }        }    }};


0 0