1-3-順時針旋轉矩陣

 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 }
相關文章
相關標籤/搜索