Q:输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下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.
A:
vector<int> printMatrix(vector<vector<int> > matrix) {
int size1 = matrix[0].size(); //列数
int size2 = matrix.size(); //行数
int left = 0, top = 0;
int right = size1 - 1, down = size2 - 1;
vector<int> array;
if(matrix.empty())
return array;
while (true) {
for (int i = left; i <= right; i++)
array.push_back(matrix[top][i]);
if (++top > down)
break;
for (int j = top; j <= down; j++)
array.push_back(matrix[j][right]);
if (--right < left)
break;
for (int m = right; m >= left; m--)
array.push_back(matrix[down][m]);
if (--down < top)
break;
for (int n = down; n >= top; n--)
array.push_back(matrix[n][left]);
if (++left > right)
break;
}
return array;
}
P.S.这个题就是如何按顺序把矩阵输出出来。
原文地址:https://www.cnblogs.com/xym4869/p/12271322.html
时间: 2024-11-09 18:05:42