剑指offer系列13:顺时针打印矩阵

这种题,必然要一圈一圈循环,因此,考虑两个问题:1.如何终止循环 2.如何打印一圈

我今天偷懒了, main函数是我从答案搬来的。

 1 #include<iostream>
 2 #include<vector>
 3 using namespace std;
 4 class Solution {
 5 public:
 6     vector<int> printMatrix(vector<vector<int> > matrix) {
 7         int row = matrix.size();
 8         int col = matrix[0].size();
 9         int left = 0, right = col-1;//列标
10         int top = 0, bot = row-1;//行标
11         vector<int>  result;
12         while (left <=right&&top <= bot)
13         {
14             //打印上面一行,列是变量
15             for (int i = left; i <= right; i++)
16             {
17                 result.push_back(matrix[top][i]);
18             }
19             //打印右边一列,行是变量
20             if (bot > top)
21             {
22                 for (int i = top+1; i <=bot; i++)
23                 {
24                     result.push_back(matrix[i][right]);
25                 }
26             }
27             //打印下边一行,列是变量
28             if (bot > top&&right > left)
29             {
30                 for (int i = right-1; i >=left; i--)
31                 {
32                     result.push_back(matrix[bot][i]);
33                     
34                 }
35             }
36             //打印左边一列,行是变量
37             if (bot-top>1  && right > left)
38             {
39                 for (int i = bot-1; i >top; i--)
40                 {
41                     result.push_back(matrix[i][left]);                
42                 }
43             }
44             top++;
45             right--;
46             bot--;
47             left++;
48 
49         }
50         return result;
51     }
52 };
53 int main()
54 {
55     int a1[] = { 1,  2,  3,  4 };
56     int a2[] = { 5,  6,  7,  8 };
57     int a3[] = { 9, 10, 11, 12 };
58     int a4[] = { 13, 14, 15, 16 };
59     //    int a1[] = { 1 };
60     //    int a2[] = { 2 };
61     //    int a3[] = { 3 };
62     //    int a4[] = { 4 };
63 
64     vector<int> vec1(a1, a1 + 4);
65     vector<int> vec2(a2, a2 + 4);
66     vector<int> vec3(a3, a3 + 4);
67     vector<int> vec4(a4, a4 + 4);
68 
69 
70     vector< vector<int> > vec;
71     vec.push_back(vec1);
72     vec.push_back(vec2);
73     vec.push_back(vec3);
74     vec.push_back(vec4);
75 
76     Solution solu;
77     vector<int> res = solu.printMatrix(vec);
78     for (int i = 0; i < res.size(); i++)
79     {
80         cout << res[i] << " ";
81     }
82     return 0;
83 }

 

posted @ 2019-06-11 15:12  妮妮熊  阅读(115)  评论(0编辑  收藏  举报