1 /* 2 题目描述: 3 对于一个矩阵,请设计一个算法从左上角(mat[0][0])开始,顺时针打印矩阵元素。 4 给定int矩阵mat,以及它的维数nxm,请返回一个数组,数组中的元素为矩阵元素的顺时针输出。 5 测试样例: 6 [[1,2],[3,4]],2,2 7 返回:[1,2,3,4] 8 */ 9 /* 10 还是要注意细节,坐标在变换的时候,应该如何增减。 11 */ 12 #include <iostream> 13 #include <vector> 14 using namespace std; 15 16 vector<int> printEdge(vector<vector<int> > mat, int t1, int t2, int d1, int d2){ 17 vector<int> frm; 18 if (t1 == d1){//子矩阵只有一行 19 for (int i = t2; i <= d2; i++) 20 frm.push_back(mat[t1][i]); 21 } 22 else if (t2 == d2){//子矩阵只有一列 23 for (int i = t1; i <= d1; i++) 24 frm.push_back(mat[i][t2]); 25 } 26 else{//一般情况 27 int svt1 = t1; 28 int svt2 = t2; 29 while(t2 < d2){ 30 frm.push_back(mat[t1][t2]); 31 t2++; 32 } 33 while (t1 <= d1){ 34 frm.push_back(mat[t1][d2]); 35 t1++; 36 } 37 while (t2 > svt2+1){ 38 t2--; 39 frm.push_back(mat[d1][t2]); 40 } 41 t2--; 42 while (t1-1 > svt1){ 43 t1--; 44 frm.push_back(mat[t1][t2]); 45 } 46 } 47 return frm; 48 } 49 vector<int> clockwisePrint(vector<vector<int> > mat, int n, int m){ 50 int t1 = 0; 51 int t2 = 0; 52 int d1 = n-1; 53 int d2 = m-1; 54 vector<int> rt; 55 while (t1 <= d1 && t2 <= d2){ 56 vector<int> edge = printEdge(mat, t1++, t2++, d1--, d2--); 57 for (int i = 0; i < edge.size(); i++) 58 rt.push_back(edge[i]); 59 } 60 return rt; 61 } 62 63 int main(){ 64 vector<vector<int> > matrix; 65 /* vector<int> a; 66 a.push_back(1); 67 a.push_back(2); 68 a.push_back(3); 69 a.push_back(4); 70 matrix.push_back(a); 71 72 vector<int> b; 73 b.push_back(5); 74 b.push_back(6); 75 b.push_back(7); 76 b.push_back(8); 77 matrix.push_back(b); 78 79 vector<int> c; 80 c.push_back(9); 81 c.push_back(10); 82 c.push_back(11); 83 c.push_back(12); 84 matrix.push_back(c); 85 86 vector<int> d; 87 d.push_back(13); 88 d.push_back(14); 89 d.push_back(15); 90 d.push_back(16); 91 matrix.push_back(d); 92 */ 93 vector<int> a; 94 a.push_back(98); 95 a.push_back(30); 96 a.push_back(17); 97 // a.push_back(4); 98 matrix.push_back(a); 99 100 vector<int> b; 101 b.push_back(38); 102 b.push_back(96); 103 b.push_back(90); 104 // b.push_back(8); 105 matrix.push_back(b); 106 107 vector<int> c; 108 c.push_back(17); 109 c.push_back(0); 110 c.push_back(50); 111 // c.push_back(12); 112 matrix.push_back(c); 113 114 vector<int> d; 115 d.push_back(44); 116 d.push_back(12); 117 d.push_back(67); 118 // d.push_back(16); 119 matrix.push_back(d); 120 121 vector<int> e; 122 e.push_back(12); 123 e.push_back(79); 124 e.push_back(43); 125 // b.push_back(8); 126 matrix.push_back(e); 127 128 vector<int> f; 129 f.push_back(43); 130 f.push_back(63); 131 f.push_back(40); 132 // c.push_back(12); 133 matrix.push_back(f); 134 135 vector<int> g; 136 g.push_back(19); 137 g.push_back(93); 138 g.push_back(48); 139 // d.push_back(16); 140 matrix.push_back(g); 141 142 vector<int> rt; 143 rt = clockwisePrint(matrix, 7, 3); 144 for (int i = 0; i < rt.size(); i++) 145 cout << rt[i] << ","; 146 cout << endl; 147 return 0; 148 }
时间: 2024-12-29 23:18:00