Leetcode算法學習日誌-48 Rotate Image

Leetcode 48 Rotate Image

題目原文

You are given an n x n 2D matrix representing an image.

Rotate the image by 90 degrees (clockwise).

Note:
You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.

Example 1:

Given input matrix = 
[
  [1,2,3],
  [4,5,6],
  [7,8,9]
],

rotate the input matrix in-place such that it becomes:
[
  [7,4,1],
  [8,5,2],
  [9,6,3]
]

題意分析

將一個方陣表示的圖像向順時針旋轉90度,方法中不能使用額外的方陣空間,也就是旋轉需要在原址操作。

解法分析

本題解法比較巧妙,對一個方陣,如果需要順時針旋轉90度,只需要先將所有的行反向排列,再對新的方陣做一次轉置。如果是逆時針旋轉,則是將所有行反向排列。C++代碼如下:

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]);
        }  
    }
};
轉置操作用swap進行,注意對角線上的元素不用操作。

發佈了79 篇原創文章 · 獲贊 16 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章