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?
一圈一圈的调整,关键是找到变换的各个坐标的关系,行变列,而行中第一个数在列中为第一个数,第二个数再列中为第二个数...第n个数在列中为第n个数;列变行,列中第一个数变为行中最后一个数,第二个数变为倒数第二个,第三变倒数第三....最后一个变为行的第一个数。
一:以下代码从列边行的角度出发写的,也就是从后往前推。
class Solution { public: void rotateSquare(vector<vector<int>>& matrix,int leftup,int rightdown) { int diff = rightdown-leftup; for(int i=0;i<diff;i++){ int tmp = matrix[leftup][leftup+i]; matrix[leftup][leftup+i] = matrix[rightdown-i][leftup];//列变行 matrix[rightdown-i][leftup] = matrix[rightdown][rightdown-i];//行变列 matrix[rightdown][rightdown-i] = matrix[leftup+i][rightdown];//列变行 matrix[leftup+i][rightdown] = tmp; } } void rotate(vector<vector<int>>& matrix) { int row = matrix.size(); if(row==0){ return; } int i=0; while(i<row){ rotateSquare(matrix,i,row-1); i++; row--; } } };
二:以下从行变列出发写,也就是从前往后推。
class Solution { public: void rotateSquare(vector<vector<int>>& matrix,int leftup,int rightdown) { int diff = rightdown-leftup; for(int i=0;i<diff;i++){ int tmp1 = matrix[leftup+i][rightdown]; matrix[leftup+i][rightdown] = matrix[leftup][leftup+i]; int tmp2 = matrix[rightdown][rightdown-i] ; matrix[rightdown][rightdown-i] = tmp1; tmp1 = matrix[rightdown-i][leftup]; matrix[rightdown-i][leftup]=tmp2; matrix[leftup][leftup+i] = tmp1; } } void rotate(vector<vector<int>>& matrix) { int row = matrix.size(); if(row==0){ return; } int i=0; while(i<row){ rotateSquare(matrix,i,row-1); i++; row--; } } };
写者:zengzy
出处: http://www.cnblogs.com/zengzy
标题有【转】字样的文章从别的地方转过来的,否则为个人学习笔记