题解 | #螺旋矩阵#
螺旋矩阵
http://www.nowcoder.com/practice/7edf70f2d29c4b599693dc3aaeea1d31
// 注意矩阵行列数不相等
class Solution {
public:
vector<int> spiralOrder(vector<vector<int> > &matrix) {
vector<int> result;
if (0==matrix.size())
return result;
int cols=matrix[0].size(), rows=matrix.size();
int right=cols-1, down=rows-1, left=0, up=0;
int i=0,j=0; //原矩阵下标
while (result.size() < cols*rows-1) {
for (up++;j<right;j++)
result.push_back(matrix[i][j]);
if (result.size() == cols*rows-1) { //针对一行
result.push_back(matrix[i][j]);
return result;
}
for (right--;i<down;i++)
result.push_back(matrix[i][j]);
for (down--;j>left;j--)
result.push_back(matrix[i][j]);
if (result.size() == cols*rows-1) { //针对一列
result.push_back(matrix[i][j]);
return result;
}
for (left++;i>up;i--)
result.push_back(matrix[i][j]);
}
result.push_back(matrix[i][j]);
return result;
}
};