https://www.nowcoder.com/practice/7edf70f2d29c4b599693dc3aaeea1d31
思路:按右、下、左、上的方向遍历矩阵,注意边界判断
class Solution {
public:
vector<int> spiralOrder(vector<vector<int> > &matrix) {
vector<int> ans;
if (!matrix.empty()) {
// m×n矩阵
int m = matrix.size(), n = matrix[0].size();
// 上、右、下、左 边界
int top = -1, right = n, down = m, left = -1;
// 遍历下标
int i = 0, j = 0;
while (true) {
// 往右走
while (j < right) {
ans.push_back(matrix[i][j++]);
}
// 更新边界
i++;j--;top++;
// 边界判断
if (top >= down-1) break;
// 往下走
while (i < down) {
ans.push_back(matrix[i++][j]);
}
i--;j--;right--;
if (left >= right-1) break;
// 往左走
while (j > left) {
ans.push_back(matrix[i][j--]);
}
i--;j++;down--;
if (top >= down-1) break;
// 往上走
while (i > top) {
ans.push_back(matrix[i--][j]);
}
i++;j++;left++;
if (left >= right-1) break;
}
}
return ans;
}
};