题解 | #螺旋矩阵#
螺旋矩阵
http://www.nowcoder.com/practice/7edf70f2d29c4b599693dc3aaeea1d31
模拟题,注意matrix只包含一行或者一列的情况,loop完之后还剩余一行或者一列的情况。
class Solution {
public:
vector<int> spiralOrder(vector<vector<int> > &matrix) {
vector<int> result{};
if(matrix.empty()) return result;
int m=matrix.size();
int n=matrix[0].size();
int loop=min(m,n)/2;
int offset=1;
int start_x{0},start_y{0},i{0},j{0};
if(loop==0){
for(auto x:matrix)
for(auto xx:x)
result.push_back(xx);
return result;
}
while(loop--){
i=start_x;
j=start_y;
for(;j<start_y+n-offset;j++) result.push_back(matrix[i][j]);
for(;i<start_x+m-offset;i++) result.push_back(matrix[i][j]);
for(;j>start_y;j--) result.push_back(matrix[i][j]);
for(;i>start_x;i--) result.push_back(matrix[i][j]);
start_x++;
start_y++;
offset+=2;
}
if(min(m,n)%2!=0 && min(m,n)==m){
i=start_x;
j=start_y;
for(;j<=start_y+n-offset;j++) result.push_back(matrix[i][j]);
}
else if(min(m,n)%2!=0 && min(m,n)==n){
i=start_x;
j=start_y;
for(;i<=start_x+m-offset;i++) result.push_back(matrix[i][j]);
}
return result;
}
};