All Problems
Algorithm Visualizer

Spiral Matrix

O(m·n) time · O(1) space · Boundary pointers
Matrix Input
3
3
Right
Down
Left
Up
5
Ready — click Run or Step
Spiral Output
— waiting for input —
Current Step 0 / 0
⏱ O(m·n) time ◻ O(1) space
Solution Code
class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        vector<int> res;
        int top = 0,  bot   = matrix.size() - 1;
        int left = 0, right = matrix[0].size() - 1;

        while (left <= right && top <= bot) {
            // → traverse top row left to right
            for (int c = left; c <= right; c++)   res.push_back(matrix[top][c]);
            top++;

            // ↓ traverse right column top to bottom
            for (int r = top; r <= bot; r++)    res.push_back(matrix[r][right]);
            right--;

            // ← traverse bottom row right to left
            if (top <= bot) {
                for (int c = right; c >= left; c--)  res.push_back(matrix[bot][c]);
                bot--;
            }

            // ↑ traverse left column bottom to top
            if (left <= right) {
                for (int r = bot; r >= top; r--)   res.push_back(matrix[r][left]);
                left++;
            }
        }
        return res;
    }
};