1 /* 2 题目描述: 3 有一个NxN整数矩阵,请编写一个算法,将矩阵顺时针旋转90度。 4 给定一个NxN的矩阵,和矩阵的阶数N,请返回旋转后的NxN矩阵,保证N小于等于300。 5 测试样例: 6 [[1,2,3],[4,5,6],[7,8,9]],3 7 返回:[[7,4,1],[8,5,2],[9,6,3]] 8 */ 9 /* 10 将矩阵顺时针旋转90度 11 一圈一圈的进行旋转(交换)。 12 eg: 13 1 2 3 14 4 5 6 15 7 8 9 16 先旋转外圈: 17 首先交换1->3->9->7->1; 18 然后交换2->6->8->4->2; 19 */ 20 #include <iostream> 21 #include <vector> 22 using namespace std; 23 24 void rotateEdge(vector<vector<int> > &m, int tr, int tc, int dr, int dc){ 25 int times = dc - tc; 26 int tmp = 0; 27 for (int i = 0; i < times; i++){ 28 tmp = m[tr][tc+i]; 29 m[tr][tc+i] = m[dr-i][tc]; 30 m[dr-i][tc] = m[dr][dc-i]; 31 m[dr][dc-i] = m[tr+i][dc]; 32 m[tr+i][dc] = tmp; 33 } 34 } 35 vector<vector<int> > rotateMatrix(vector<vector<int> > mat, int n) { 36 // write code here 37 int tR = 0; 38 int tC = 0; 39 int dR = n-1; 40 int dC = n-1; 41 while (tR < dR){ 42 rotateEdge(mat, tR++, tC++, dR--, dC--); 43 } 44 return mat; 45 } 46 int main(){ 47 vector<vector<int> > matrix; 48 vector<int> a; 49 a.push_back(1); 50 a.push_back(2); 51 a.push_back(3);/* 52 a.push_back(4);*/ 53 matrix.push_back(a); 54 55 vector<int> b; 56 b.push_back(4); 57 b.push_back(5); 58 b.push_back(6);/* 59 b.push_back(8);*/ 60 matrix.push_back(b); 61 62 vector<int> c; 63 c.push_back(7); 64 c.push_back(8); 65 c.push_back(9);/* 66 c.push_back(12);*/ 67 matrix.push_back(c); 68 69 vector<vector<int> > rt; 70 rt = rotateMatrix(matrix,3); 71 for (int i = 0; i < 3; i++){ 72 for (int j = 0; j < 3; j++) 73 cout << rt[i][j] << ","; 74 cout << endl; 75 } 76 return 0; 77 }