[剑指Offer] 19.顺时针打印矩阵

【思路】本题关键在于 右->左 和 下->上 两个循环体中的判断条件,即判断是否重复打印。

 1 class Solution
 2 {
 3 public:
 4     vector<int> printMatrix(vector<vector<int> > matrix)
 5     {
 6         int col = matrix[0].size();
 7         int row = matrix.size();
 8         int num = (((row <= col)?row:col) - 1)/2 + 1;
 9         vector<int> res;
10         res.clear();
11         for(int x = 0; x < num; x ++)
12         {
13             //左->右            
14             for(int i = x; i < col - x; i ++)
15             {
16                 res.push_back(matrix[x][i]);
17             }            
18             //上->下           
19             for(int i = x + 1; i < row - x; i ++)
20             {
21                 res.push_back(matrix[i][col - 1 - x]);
22             }            
23             //右->左           
24             for(int i = col - 2 - x; (i >= x) && (row - 1 - x != x); i --)
25             {
26                 res.push_back(matrix[row - 1 - x][i]);
27             }            
28             //下->上         
29             for(int i = row - 2 - x; (i > x) && (x != col - 1 - x); i --)
30             {
31                 res.push_back(matrix[i][x]);
32             }        
33         }        
34         return res;
35     }
36 };

 

posted @ 2017-02-28 17:09  Strawberry丶  阅读(197)  评论(0编辑  收藏  举报