forked from haoel/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 39
/
rotateImage.cpp
73 lines (63 loc) · 1.68 KB
/
rotateImage.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
// Source : https://oj.leetcode.com/problems/rotate-image/
// Author : Hao Chen
// Date : 2014-06-27
/**********************************************************************************
*
* 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?
*
**********************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <vector>
using namespace std;
void rotate(vector<vector<int> > &matrix) {
int n = matrix.size();
for( int i=0; i<n/2; i++ ){
int low=i, high=n-i-1;
for (int j=low; j<high; j++){
int tmp;
tmp = matrix[i][j];
// left to top
matrix[i][j] = matrix[n-j-1][i];
// bottom to left
matrix[n-j-1][i] = matrix[n-i-1][n-j-1];
// right to bottom
matrix[n-i-1][n-j-1] = matrix[j][n-i-1];
// top to right
matrix[j][n-i-1] = tmp;
}
}
}
void printMatrix(vector<vector<int> > &matrix)
{
for(int i=0; i<matrix.size(); i++){
for(int j=0; j< matrix[i].size(); j++) {
printf("%3d ", matrix[i][j]) ;
}
cout << endl;
}
cout << endl;
}
int main(int argc, char** argv)
{
int n = 2;
if (argc>1){
n = atoi(argv[1]);
}
vector< vector<int> > matrix;
for (int i=1; i<=n; i++) {
vector<int> v;
for(int j=1; j<=n; j++){
v.push_back( (i-1)*n + j );
}
matrix.push_back(v);
}
printMatrix(matrix);
rotate(matrix);
printMatrix(matrix);
return 0;
}