Rotate Image

来源:互联网 发布:silverlight mac版本 编辑:程序博客网 时间:2024/06/07 17:38

一、问题描述

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?

二、思路

矩阵旋转90度。原理如下:先上下翻转,再交换对角元素即可。

 * 1 2 3     7 8 9     7 4 1 * 4 5 6  => 4 5 6  => 8 5 2 * 7 8 9     1 2 3     9 6 3

三、代码

class Solution {public:    void rotate(vector<vector<int>>& matrix) {        reverse(matrix.begin(), matrix.end());        for(int i = 0; i < matrix.size();++i){            for(int j = i + 1; j < matrix[i].size();++j){                swap(matrix[i][j],matrix[j][i]);            }        }    }};


在评论区看到另外一种思路:先左右翻转,然后交换对角元素。

* 1 2 3     3 2 1     3 6 9 * 4 5 6  => 6 5 4  => 2 5 8 * 7 8 9     9 8 7     1 4 7

void anti_rotate(vector<vector<int> > &matrix) {    for (auto vi : matrix) reverse(vi.begin(), vi.end());    for (int i = 0; i < matrix.size(); ++i) {        for (int j = i + 1; j < matrix[i].size(); ++j)            swap(matrix[i][j], matrix[j][i]);    }}



1 0