19顺时针打印矩阵

 1 顺时针打印矩阵
 2 //题目:输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵: 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.
 3 class Solution
 4 {
 5 public:
 6     vector<int> printMatrix(vector<vector<int>> matrix)
 7     {
 8         int rows = matrix.size(); //矩阵的行
 9         int cols = matrix[0].size(); //矩阵的列
10         vector<int> tmpVec;
11         //输入的二维数组非法,返回空的数组
12         if (rows <= 0 || cols <= 0)
13         {
14             return tmpVec;
15         }
16         //左上角为startLeft
17         int startLeft = 0;
18         //右上角的startRight
19         int startRight = cols - 1;
20         //
21         int top = 0;
22         //
23         int bottom = rows -1;
24         while(startLeft <= startRight && top <= bottom)
25         {
26             //从左向右
27             for (int i = startLeft; i<=startRight; ++i)
28             {
29                 tmpVec.push_back(matrix[startLeft][i]);
30             }
31             //从上到下
32             for (int i = top+1; i <= bottom; ++i)
33             {
34                 tmpVec.push_back(matrix[i][startRight]);
35             }
36             //从右到左(只有top == bottom,表示只有一行,该行也遍历过)
37             if(top != bottom)
38             {
39                 for (int i = startRight-1; i >=startLeft; --i)
40                 {
41                     tmpVec.push_back(matrix[bottom][i]);
42                 }
43             }
44             //从下向上(只有startLeft == startRight,表示只有列,该列也遍历过)
45             if (startLeft != startRight)
46             {
47                 for (int i = bottom-1; i>= top+1 ;--i)
48                 {
49                     tmpVec.push_back(matrix[i][startLeft]);
50                 }
51             }
52             startLeft++; 
53             top++;
54             startRight--;
55             bottom--;
56         }
57         return tmpVec;
58     }
59 };

 

posted @ 2017-08-21 11:56  繁星的夜空2012  阅读(104)  评论(0编辑  收藏  举报