剑指offer 顺时针打印矩阵

剑指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> printMatrix(vector<vector<int>> matrix) {
 4         int row=matrix.size();
 5         int col=matrix[0].size();
 6         vector<int> result;
 7         if(row==0||col==0)
 8             return result;
 9         int left=0,right=col-1,top=0,btm=row-1;
10         while(left<=right&&top<=btm)
11             {
12             for(int i=left;i<=right;i++)
13                 result.push_back(matrix[top][i]);
14             if(top<btm)
15                 for(int i=top+1;i<=btm;i++)
16                     result.push_back(matrix[i][right]);
17             if(top<btm&&left<right)
18                 for(int i=right-1;i>=left;i--)
19                     result.push_back(matrix[btm][i]);
20             if(top+1<btm&&left<right)
21                 for(int i=btm-1;i>=top+1;i--)
22                     result.push_back(matrix[i][left]);
23             left++;right--;top++;btm--;
24         }
25         return result;
26     }
27 };

我的笔记:根据数组规律,可设四个位置标点,并进行四种循环;(1)从左至右遍历;(2)从上至下遍历;(3)从右至左遍历;(4)从下至上遍历。四种循环后将四个位置标点逐个更改,并再每次循环之前判断标点位置是否过界。