剑指offer 顺时针打印矩阵

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下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 class Solution {
 2 public:
 3     vector<int> ans;
 4     int row,col;
 5     vector<int> printMatrix(vector<vector<int> > matrix) {
 6         
 7         row = matrix.size();
 8         col = matrix[0].size();
 9         int top = 0, bottom = row-1,left = 0,right = col-1;
10         while(top <= bottom && left <= right){
11             for(int i = left; i <= right; i++)
12                 ans.push_back(matrix[top][i]);
13             for(int i = top+1; i <= bottom; i++)
14                 ans.push_back(matrix[i][right]);
15             if(top < bottom)
16                 for(int i = right-1; i >= left; i--)
17                     ans.push_back(matrix[bottom][i]);
18             if(left < right)
19                 for(int i = bottom-1; i > top; i--)
20                     ans.push_back(matrix[i][left]);
21             left++,right--,top++,bottom--;
22         }
23         return ans;
24     }
25     
26 };

 

posted @ 2019-08-16 23:00  TTTCoder  阅读(209)  评论(0编辑  收藏  举报