题意
顺时针输出矩阵元素到一个一维向量中
题解
x,y记录矩阵最左上角坐标,n、m记录最右下角坐标,不断缩小矩阵
代码
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> result;
if(matrix.empty())
return result;
int n = matrix.size() - 1, m = matrix[0].size() - 1;
for(int x = 0, y = 0; x <= n && y <= m; x++,y++ )
{
for(int j = y; j <= m; j++)
result.push_back(matrix[x][j]);
for(int i = x + 1; i <= n; i++)
result.push_back(matrix[i][m]);
if(x != n)
{
for(int j = m - 1; j >= y; j--)
result.push_back(matrix[n][j]);
}
if(y != m)
{
for(int i = n - 1; i > x; i--)
result.push_back(matrix[i][y]);
}
n--,m--;
}
return result;
}
};