Leetcode Daily Problem
54. Spiral Matrix
Given an m x n
matrix
, return all elements of the matrix
in spiral order.
In this question, we will use four indices startrow=0, startcol=0, endrow=n-1, and endcol=m-1.
vector<int> spiralOrder(vector<vector<int>>& matrix)
{
vector<int> res;
int n = matrix.size();
int m = matrix[0].size();
int row1 = 0;
int row2 = n-1;
int col1 = 0;
int col2 = m-1;
while( row1<=row2 && col1<=col2)
{
for(int j=col1;j<=col2;j++)
{
res.push_back(matrix[row1][j]);
}
for(int j=row1+1;j<=row2;j++)
{
res.push_back(matrix[j][col2]);
}
for(int j=col2-1;j>=col1;j--)
{
if(row1==row2)
{
break;
}
res.push_back(matrix[row2][j]);
}
for(int j=row2-1;j>=row1+1;j--)
{
if(col1==col2)
{
break;
}
res.push_back(matrix[j][col1]);
}
row1++;
col1++;
row2--;
col2--;
}
return res;
}