之前几天在看吴恩达,LeetCode停了几天,今天重新开始,希望之后每天能抽出时间写几道。
这道题目是剑指offer上的第29题,顺势正打印矩阵。题目给出一个由数组构成的矩阵,要求顺时针顺序从里到外打印出每一个数字,代码如下:
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
if (matrix.size() == 0 || matrix[0].size() == 0) {
return {};
} //判断举证是否为空
int n = matrix.size();//读取举证的列数
int m = matrix[0].size();//读取矩阵的行数
int size = m*n;//矩阵总共含有的元素个数
vector<int> answer(size);//创建答案数组
int count = 0;//创建下表
//创建矩阵的上下左右,循环一圈以后,上下左右的值分别向内收缩
int left = 0;
int right = m - 1;
int top = 0;
int bottom = n - 1;
while(right >= left && bottom >= top)
{
for(int column = left; column <= right ; ++column)
{
answer[count++] = matrix[top][column];
}
for(int row = top + 1; row <= bottom; ++row)
{
answer[count++] = matrix[row][right];
}
if(right > left && bottom > top)
{
for(int column = right - 1; column >= left; --column)
{
answer[count++] = matrix[bottom][column];
}
for(int row = bottom - 1; row > top; --row)
{
answer[count++] = matrix[row][left];
}
}
//向内收随
left++;
right--;
top++;
bottom--;
}
return answer;
}
};