题目描述
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下4 X 4矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.
解题思路:按照一圈一圈的打印
参考答案:
复制代码
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117#include <iostream> #include <vector> #include <string> #include <stack> #include <algorithm> #include <math.h> using namespace std; class Solution { public: vector<int> printMatrix(vector<vector<int> > matrix) { vector<int> my_result; int row = matrix.size();//行 int col = matrix[0].size();//列 if (row == 0 || col == 0) return my_result; int i_start = 0,i_end; int j_start = 0,j_end; i_end = col-1; j_end = row-1; while (i_start <= i_end && j_start <= j_end) { //上面那一行(从左往右打印) for (int i = i_start; i <= i_end; ++i) { my_result.push_back(matrix[j_start][i]); } //右侧那一列(从上往下打印) if (j_start < j_end) { for (int i = j_start+1; i <= j_end; ++i) { my_result.push_back(matrix[i][i_end]); } } //下面那一行(从右往左打印) if (i_start < i_end && j_start < j_end) { for (int i = i_end-1; i >= i_start; --i) { my_result.push_back(matrix[j_end][i]); } } //左侧那一列(从下往上打印) if (i_start < i_end && j_start+1 <j_end) { for (int i = j_end-1; i > j_start; --i) { my_result.push_back(matrix[i][i_start]); } } i_end--; i_start++; j_start++; j_end--; } return my_result; } }; int main() { vector<int> my_m; vector<int> result; vector<vector<int> > my_matrix; int count; my_m.push_back(1); my_m.push_back(2); my_m.push_back(3); my_m.push_back(4); my_matrix.push_back(my_m); my_m.clear(); my_m.push_back(5); my_m.push_back(6); my_m.push_back(7); my_m.push_back(8); my_matrix.push_back(my_m); my_m.clear(); my_m.push_back(9); my_m.push_back(10); my_m.push_back(11); my_m.push_back(12); my_matrix.push_back(my_m); my_m.clear(); my_m.push_back(13); my_m.push_back(14); my_m.push_back(15); my_m.push_back(16); my_matrix.push_back(my_m); my_m.clear(); Solution solution; result = solution.printMatrix(my_matrix); // cout<<"my_matrix:"<<result[4]<<endl; count = 0; while (count < result.size()) { cout<<" "<<result[count]; count++; } return 0; }
最后
以上就是美丽中心最近收集整理的关于牛客网-C++剑指offer-第十九题(顺时针打印矩阵)的全部内容,更多相关牛客网-C++剑指offer-第十九题(顺时针打印矩阵)内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复