首页 > 其他 > 详细

Rotate Image

时间:2014-04-06 07:08:28      阅读:476      评论:0      收藏:0      [点我收藏+]

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

bubuko.com,布布扣
 1 class Solution {
 2 public:
 3     void rotate(vector<vector<int> > &matrix) {
 4         rotate_2(matrix);
 5     }
 6     
 7     void rotate_1(vector<vector<int> > &matrix) {
 8         int n = matrix.size();
 9         for (int i = 0; i < (n + 1) / 2; i++)
10             for (int j = 0; j < n / 2; j++)
11                 rotateElement(matrix, i, j);
12     }
13     void rotateElement(vector<vector<int> > &matrix, int row, int col)
14     {
15         int temp = matrix[row][col];
16         for (int i = 0; i < 3; i++) {
17             int c = row;
18             int r = matrix.size() - 1 - col;
19             matrix[row][col] = matrix[r][c];
20             row = r;
21             col = c;
22         }
23         matrix[row][col] = temp;
24     }
25     
26     void rotate_2(vector<vector<int> > &matrix) {
27         int N = matrix.size();
28         for (int i = 0; i < N; ++i)
29             for (int j = i+1; j < N; ++j)
30                 swap(matrix[i][j], matrix[j][i]);
31         for (int j = 0; j < N/2; ++j)
32             for (int i = 0; i < N; ++i)
33                 swap(matrix[i][j], matrix[i][N-j-1]);
34     }
35 };
bubuko.com,布布扣

 

Rotate Image,布布扣,bubuko.com

Rotate Image

原文:http://www.cnblogs.com/zhengjiankang/p/3647899.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!