题解 | #螺旋矩阵#
螺旋矩阵
https://www.nowcoder.com/practice/7edf70f2d29c4b599693dc3aaeea1d31?tpId=295&tqId=693&ru=%2Fpractice%2Fe19927a8fd5d477794dac67096862042&qru=%2Fta%2Fformat-top101%2Fquestion-ranking&sourceUrl=%2Fexam%2Foj
不断缩小边界
class Solution {
public:
vector<int> spiralOrder(vector<vector<int> > &matrix) {
if (matrix.empty()) {
return std::vector<int>();
}
std::vector<int> res;
int left = 0, right = matrix[0].size() - 1, up = 0, down = matrix.size() - 1;
while (left <= right && up <= down) {
for (int i = left; i <= right; ++i) {
res.push_back(matrix[up][i]);
}
++up;
if (up > down) {
break;
}
for (int i = up; i <= down; ++i) {
res.push_back(matrix[i][right]);
}
--right;
if (left > right) {
break;
}
for (int i = right; i >= left; --i) {
res.push_back(matrix[down][i]);
}
--down;
if (up > down) {
break;
}
for (int i = down; i >= up; --i) {
res.push_back(matrix[i][left]);
}
++left;
if (left > right) {
break;
}
}
return res;
}
};
