Sunday, May 10, 2015

Rotate Image

来源:Leetcode

原帖:http://oj.leetcode.com/problems/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?
Solution: 1. Rotate one-fourth of the image clockwise.
                2. 123       147   ->   741    (preferable)
                    456  ->   258        852
                    789       369        963
                3. Rotate 4-corners of the images from outer to inner

代码:
1] Rotate 1/4 of the image
 class Solution {  
 public:  
   //Rotate 1/4 of the image  
   void rotate(vector<vector<int> > &matrix) {  
     int n = matrix.size();  
     for (int i = 0; i < (n + 1) / 2; i++)  
       for (int j = 0; j < n / 2; j++)  
         rotateElement(matrix, i, j);  
   }  
     
   void rotateElement(vector<vector<int> > &matrix, int row, int col) {  
     int temp = matrix[row][col];  
     for (int i = 0; i < 3; i++) {  
       int r = matrix.size() - 1 - col;  
       int c = row;  
       matrix[row][col] = matrix[r][c];  
       row = r;  
       col = c;  
     }  
     matrix[row][col] = temp;  
   }  
 };  

2] 对角线,垂直中心交换
 class Solution {  
 public:  
   //对角线,垂直中心交换  
   void rotate(vector<vector<int> > &matrix) {  
     int N = matrix.size();  
     for (int i = 0; i < N; ++i) {  
       for (int j = i + 1; j < N; ++j) {  
         swap(matrix[i][j], matrix[j][i]); // swap diagnol elements                
       }  
     }  
     for (int j = 0; j < N / 2; ++j) { // cols  
       for (int i = 0; i < N; ++i) { // rows  
         swap(matrix[i][j], matrix[i][N - j - 1]);  
       }  
     }  
   }  
 };  

3] 从外层向内层旋转
 class Solution {  
 public:  
   //从外层向内层旋转  
   void rotate(vector<vector<int> > &matrix) {  
     if (matrix.empty() || matrix[0].empty()) return;      
     int N = matrix.size();  
     for (int i = 0; i < N / 2; ++i) {  
       for (int j = i; j < N - i - 1; ++j) {  
         int tmp = matrix[i][j];  
         matrix[i][j] = matrix[N - j - 1][i];  
         matrix[N - j - 1][i] = matrix[N - i - 1][N - j - 1];  
         matrix[N - i - 1][N - j - 1] = matrix[j][N - i - 1];  
         matrix[j][N - i - 1] = tmp;  
       }  
     }  
   }  
 };  

No comments:

Post a Comment