# [54\. Spiral Matrix](https://leetcode.com/problems/spiral-matrix/) :::spoiler Solution ```cpp= class Solution { public: vector<int> spiralOrder(vector<vector<int>>& matrix) { int up = 0, down = matrix.size() - 1; int left = 0, right = matrix[0].size() - 1; vector<int> res; int direction = 0; while (true) { if (direction == 0) { for (int i = left; i <= right; ++i) { res.push_back(matrix[up][i]); } ++up; } else if (direction == 1) { for (int i = up; i <= down; ++i) { res.push_back(matrix[i][right]); } --right; } else if (direction == 2) { for(int i = right; i >= left; i--) { res.push_back(matrix[down][i]); } --down; } else { for(int i = down; i >= up; i--) { res.push_back(matrix[i][left]); } ++left; } if (up > down || left > right) break; direction = (direction + 1) % 4; } return res; } }; ``` - T: $O(M \dot N)$ - S: $O(M \dot N)$ :::
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up