程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> 關於C++ >> [LeetCode從零單刷]Rotate Image

[LeetCode從零單刷]Rotate Image

編輯:關於C++

題目:

 

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?

解答:

一開始想的很復雜,希望找到一個通式應對所有角度的旋轉。所有的細節寫在《【圖像處理】基於OpenCV底層實現的圖片旋轉》。

其實沒有必要,因為90度是非常特殊的一種旋轉,可以直觀上賦值:

 

class Solution {
public:
    void rotate(vector>& matrix) {
        int m = matrix.size();
        int n = matrix[0].size();
        vector tmp(m, 0);
        vector> ans(n, tmp);
        for(int i=0; i

 

但仔細看題目要求:in-place(原地)。想了半天沒想出來原地旋轉的方法。直到看到巧妙做法:傳送門。精粹就在下圖中:

\

 

class Solution {
public:
    void rotate(vector > &matrix) {
        int i,j,temp;
        int n=matrix.size();
        // 沿著副對角線反轉
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < n - i; ++j) {
                temp = matrix[i][j];
                matrix[i][j] = matrix[n - 1 - j][n - 1 - i];
                matrix[n - 1 - j][n - 1 - i] = temp;
            }
        }
        // 沿著水平中線反轉
        for (int i = 0; i < n / 2; ++i){
            for (int j = 0; j < n; ++j) {
                temp = matrix[i][j];
                matrix[i][j] = matrix[n - 1 - i][j];
                matrix[n - 1 - i][j] = temp;
            }
        }
    }
};
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved