Friday, August 5, 2016

48. Rotate Image

The 90 degree rotation can be down by following two steps:
1. swap numbers along the diagonal.
2. swap numbers along the middle column.

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

No comments:

Post a Comment