问题:输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵:1,2,3,4,5,6,7,8,9,则依次输出1,2,3,6,9,8,7,4,5
思路:利用循环,控制循环条件即可
具体代码如下:(C++)
class Solution
{
public:
vector<int> printMatrix(vector<vector<int>> matrix)
{
int rows, columns;
if(matrix.size() > 0)
{
rows = matrix.size();
columns = matrix[0].size();
}
vector<int> res; //由于保存结果
int startX = 0, endX = columns -1;
int startY = 0, endY = rows -1;
while(startX <= endX && startY <= endY)
{
if(startX <= endX && startY <= endY)
{
for(int i = startX; i<= endX; i++)
res.push_back(matrix[startY][i]); //上一行
++startY;
}
if(startY <= endY && startX <=endX)
{
for(int i = startY; i<=endY; i++)
res.push_back(matrix[i][endX]); //右一列
--endX;
}
if(startX <= endX && startY <= endY)
{
for(int i =endX; i>=startX; i--)
res.push_back(matrix[endY][i]); //下一行
--endY;
}
if(startY <= endY && startX <= endX)
{
for(int i=endY;i>= startY;i--)
res.push_back(matrix[i][startX]); //左一列
++startX;
}
}
return res;
}
};