[Leetcode 66] 48 Rotate Image

Problem:

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?

 

Analysis:

Please reference the answer on stackoverflow. 

http://stackoverflow.com/questions/3488691/how-to-rotate-a-matrix-90-degrees-without-using-any-extra-space

Transpose and interchange rows or columns (depends whether you want to rotate left or right).

It's a totally in-place version.

 

1) original matrix

1 2 3
4 5 6
7 8 9

2) transpose

1 4 7
2 5 8
3 6 9

3-a) change rows to rotate left

3 6 9
2 5 8
1 4 7

3-b) or change columns to rotate right

7 4 1
8 5 2
9 6 3

Code:

 1 class Solution {
 2 public:
 3     void rotate(vector<vector<int> > &matrix) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         int tmp;
 7         
 8         // transpose the matrix
 9         for (int i=0; i<matrix.size(); i++) {
10             for (int j=i+1; j<matrix.size(); j++) {
11                 tmp = matrix[i][j];
12                 matrix[i][j] = matrix[j][i];
13                 matrix[j][i] = tmp;
14             }
15         }
16         
17         // switch columns
18         for (int i=0, j=matrix.size()-1; i<j; i++, j--) {
19             for (int k=0; k<matrix.size(); k++) {
20                 tmp = matrix[k][i]; 
21                 matrix[k][i] = matrix[k][j];
22                 matrix[k][j] = tmp;
23             }
24         }
25     }
26 };
View Code

 

posted on 2013-07-16 09:45  freeneng  阅读(210)  评论(0编辑  收藏  举报

导航