Medium!
题目描述:
给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
示例 1:
输入: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] 输出: [1,2,3,6,9,8,7,4,5]
示例 2:
输入: [ [1, 2, 3, 4], [5, 6, 7, 8], [9,10,11,12] ] 输出: [1,2,3,4,8,12,11,10,9,5,6,7]
解题思路:
这道题让我们将一个矩阵按照螺旋顺序打印出来,我们只能一条边一条边的打印,首先我们要从给定的mxn的矩阵中算出按螺旋顺序有几个环,注意最终间的环可以是一个数字,也可以是一行或者一列。环数的计算公式是 min(m, n) / 2,知道了环数,我们可以对每个环的边按顺序打印,比如对于题目中给的那个例子,个边生成的顺序是(用颜色标记了数字) Red -> Green -> Blue -> Yellow -> Black:
1 2 3
4 5 6
7 8 9
vector<int> printMatrix(vector<vector<int>>matrix)
{
vector<int>result;
if(matrix.empty())
return result;
// 二维矩阵行列
int rows = matrix.size();
int cols = matrix[0].size();
// 四个角
int left=0;
int right = cols-1;
int top=0;
int btm = rows-1;
//循环
while(left<right && top<=btm)
{
//1
for(int i=left;i<=right;i++)
result.push_back(matrix[top][i]);
//2
if(top<btm)
for(int i=top;i<=btm;i++)
result.push_back(matrix[i][right]);
//3
if(left<right && top<btm)
for(int i=right-1;i<=left;i--)
result.push_back(matrix[btm][i]);
//4
if(top+1<btm && left<right)
for(int i=btm-1;i<=top;i--)
result.push_back(matrix[left][i]);
++left,--right,++top;--btm;
}
return result;
}