https://leetcode-cn.com/problems/spiral-matrix/
執(zhí)行用時:0 ms, 在所有 C++ 提交中擊敗了100.00%的用戶
內(nèi)存消耗:6.5 MB, 在所有 C++ 提交中擊敗了92.75%的用戶
由于每一圈的loop范圍可以由左上角坐標(biāo)和右下角坐標(biāo)確定,因此可以由這兩個坐標(biāo)值控制大循環(huán),在每次循環(huán)內(nèi),分四個方向轉(zhuǎn)圈打印,要特別注意的是當(dāng)只剩一行或一列的時候,要在合適的位置break

每一圈依次在四個方向打印
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> ret;
int rows = matrix.size();
int cols = matrix[0].size();
int left = 0;
int top = 0;
int right = cols - 1;
int bottom = rows - 1;
while (left <= right && top <= bottom) {
// 從左到右
for (int i = left; i <= right; ++i) {
ret.push_back(matrix[top][i]);
}
if (top == bottom) break;
// 從上到下
for (int i = top + 1; i <= bottom - 1; ++i) {
ret.push_back(matrix[i][right]);
}
// 從右到左
for (int i = right; i >= left; --i) {
ret.push_back(matrix[bottom][i]);
}
if (left == right) break;
// 從下到上
for (int i = bottom - 1; i >= top + 1; --i) {
ret.push_back(matrix[i][left]);
}
++left;
++top;
--right;
--bottom;
}
return ret;
}
};