剑指Offer-顺时针打印矩阵

题目:

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵: 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.

 

思路:

  首先确定矩阵的行数和列数,初始化4个变量:left = 0;right = col-1;top = 0;bottom = row-1。然后按照从左向后、从上向下、从右向左、从下向上的顺序打印即可。需要注意的是,在打印从右向左时,需要判断top是否等于bottom;若相等,则不必打印该行;在打印从下向上时,需要判断left是否等于right,若相等,则不必打印该列。

 

代码:

 1 class Solution {
 2 public:
 3     vector<int> printMatrix(vector<vector<int> > matrix) {
 4         int bottom = matrix.size() - 1;
 5         int right = matrix[0].size() - 1;
 6         int left = 0;
 7         int top = 0;
 8         vector<int> result;
 9         while (left <= right && top <= bottom) {
10             //从左向右
11             for (int i = left; i <= right; i++)
12                 result.push_back(matrix[top][i]);
13             //从上向下
14             for (int i = top + 1; i <= bottom; i++)
15                 result.push_back(matrix[i][right]);
16             if (top != bottom)
17                 //从右向左
18                 for (int i = right - 1; i >= left; i--)
19                     result.push_back(matrix[bottom][i]);
20             if (left != right)
21                 //从下向上
22                 for (int i = bottom - 1; i >= top + 1; i--)
23                     result.push_back(matrix[i][left]);
24             left++;
25             right--;
26             top++;
27             bottom--;
28         }
29         return result;
30     }
31 };
View Code

 

posted @ 2017-08-18 18:53  Sindyang  阅读(146)  评论(0编辑  收藏  举报