Skip to content
thesarfo

Reference

Spiral Traversal of a Matrix

Printing a matrix in spiral order using four shrinking boundaries.

views 0

Print an n×m matrix in spiral order (top row left-to-right, right column top-to-bottom, bottom row right-to-left, left column bottom-to-top, then inward). (LeetCode 54)

Matrix spiral traversal

Maintain four shrinking boundaries — top, bottom, left, right — and print one edge per step, moving the corresponding boundary inward each time.

class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
if (matrix.empty() || matrix[0].empty()) return {};
int n = matrix.size();
int m = matrix[0].size();
int left = 0, right = m - 1;
int top = 0, bottom = n - 1;
vector<int> ans;
while (top <= bottom && left <= right) {
for (int i = left; i <= right; i++) ans.push_back(matrix[top][i]);
top++;
for (int i = top; i <= bottom; i++) ans.push_back(matrix[i][right]);
right--;
if (top <= bottom) {
for (int i = right; i >= left; i--) ans.push_back(matrix[bottom][i]);
bottom--;
}
if (left <= right) {
for (int i = bottom; i >= top; i--) ans.push_back(matrix[i][left]);
left++;
}
}
return ans;
}
};

The if (top <= bottom) / if (left <= right) guards on the last two edges matter — without them, a matrix with a single remaining row or column would get double-printed.