本文主要是介绍Leetcode95: Rotate Image,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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?
举一个二维数组变换的例子就知道变换的坐标由a[i][j]->a[j][n-1-i]
最笨的办法就是复制数组然后再重新赋值
class Solution {
public:void rotate(vector<vector<int>>& matrix) {int n = matrix.size();vector<vector<int> > tmp(n, vector<int>(n));for(int i = 0; i < n; i++){for(int j = 0; j < n; j++){tmp[i][j] = matrix[i][j];}}for(int i = 0; i < n; i++){for(int j = 0; j < n; j++){matrix[j][n-1-i] = tmp[i][j];}}}
};
然后在网上看到一个技巧,把数组先沿着中间一行上下对调,然后沿着对角线对调即可,不用开辟新的空间存储。
class Solution {
public:void rotate(vector<vector<int>>& matrix) {int n = matrix.size();int tmp;for(int i = 0; i < n/2; i++){for(int j = 0; j < n; j++){tmp = matrix[i][j];matrix[i][j] = matrix[n-1-i][j];matrix[n-1-i][j] = tmp;}}for(int i = 0; i < n; i++){for(int j = 0; j < i; j++){tmp = matrix[i][j];matrix[i][j] = matrix[j][i];matrix[j][i] = tmp;}}}
};
这篇关于Leetcode95: Rotate Image的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!