题目描述
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下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.
思路:
模拟题,划定好每一次打印圈的边界(上下左右),注意最后一圈有可能上下左右重叠
class Solution
{
public:
vector<
int> printMatrix(vector<vector<
int>>
matrix)
{
int bottom = matrix.size() -
1;
int right = matrix[
0].size() -
1;
vector<
int>
res;
if (bottom <
0 || right <
0)
return res;
int top =
0, left =
0;
while (left <= right && top <=
bottom)
{
// 左到右
for (
int i = left; i <= right; i++
)
res.push_back(matrix[top][i]);
// 上到下
for (
int j = top +
1; j <= bottom; j++
)
res.push_back(matrix[j][right]);
// 右到左
if (top !=
bottom)
for (
int k = right -
1; k >= left; k--
)
res.push_back(matrix[bottom][k]);
// 下到上
if (left !=
right)
for (
int l = bottom -
1; l > top; l--
)
res.push_back(matrix[l][left]);
left++, top++, right--, bottom--
;
}
return res;
}
};
转载于:https://www.cnblogs.com/ruoh3kou/p/10053947.html
相关资源:数据结构—成绩单生成器