[Leetcode 48, medium] Rotate Image

来源:互联网 发布:国务卿女士 知乎 编辑:程序博客网 时间:2024/05/01 01:27

Problem:

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?

Analysis:


Solutions:

C++:

    void SwapClockwise(int &lu, int &lb, int &ru, int &rb)    {        swap(lu, ru);        swap(lb, rb);        swap(lu, rb);    }    void rotate(vector<vector<int> > &matrix) {        int n = matrix.size();        if(n <= 1)            return;                    for(int upper = 0, lower = n - 1; upper < lower; ++upper, --lower) {            for(int start = upper; start < lower; ++start) {                int &lu = matrix[upper][start];                int &ru = matrix[start][lower];                int &lb = matrix[n - 1 - start][upper];                int &rb = matrix[lower][n - 1 - start];                                SwapClockwise(lu, lb, ru, rb);            }        }    }
Java:


Python:

0 0
原创粉丝点击