LeetCode48 Rotate Image

题目:

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

Rotate the image by 90 degrees (clockwise). (Medium)

Follow up:
Could you do this in-place?

分析:

就是在纸上画一画找到对应关系即可, newMatrix[i][j] = matrix[n - 1 - j][i];

所以简单的方法就是开一个新数组,按照对应关系填入新数组,再拷贝回原来的数组。

代码:

 1 class Solution {
 2 public:
 3     void rotate(vector<vector<int>>& matrix) {
 4         vector<vector<int>> temp = matrix;
 5         for (int i = 0; i < temp.size(); ++i) {
 6             for (int j = 0; j < temp[0].size(); ++j) {
 7                 temp[i][j] = matrix[temp.size() - 1 - j][i];
 8             }
 9         }
10         for (int i = 0; i < matrix.size(); ++i) {
11             for (int j = 0; j < matrix[0].size(); ++j) {
12                 matrix[i][j] = temp[i][j];
13             }
14         }
15         return;
16     }
17 };

题目中的follow-up,要in-place,考虑原数组上如何处理。

要在原数组上处理局部交换感觉就不好想了(会交换完丢元素),把数组整体一起处理好一些。

再观察对应关系,只需要横纵坐标先颠倒,然后纵坐标上下翻转即可。

代码:

 1 class Solution {
 2 public:
 3     void rotate(vector<vector<int>>& matrix) {
 4         for (int i = 0; i < matrix.size(); ++i) {
 5             for (int j = 0; j < i; ++j) {
 6                 swap(matrix[i][j], matrix[j][i]);
 7             }
 8         }
 9         for (int j = 0; j < matrix.size() / 2; ++j) {
10             for (int i = 0; i < matrix[0].size(); ++i) {
11                 swap(matrix[i][j], matrix[i][matrix.size() - 1 - j]);
12             }
13         }
14         return;
15     }
16 };
 
原文地址:https://www.cnblogs.com/wangxiaobao/p/5843974.html