Spiral Matrix Traversal: Avoiding Off-By-One Bugs on Rectangular Grids
Rectangular ($m \times n$) matrix ko spiral order mein traverse karne mein sab se common bug top-to-bottom aur right-to-left loops chalate waqt aata hai. Agar pehle do loops (left -> right aur top -> bottom) ne boundary ko update karne ke baad top > bottom ya left > right kar diya ho, to pichle do loops bina check ke extra row ya column dobara print kar dete hain—khaskar jab m != n ho.
Is se bachne ke liye four boundaries (top, bottom, left, right) rakhein, har direction ke baad boundary ko inward move karein, aur neeche/baayein (bottom/right) wale do loops se pehle explicit boundary condition (top <= bottom aur left <= right) check karein.
Why Off-By-One Bugs Happen on $m \times n$ Grids
Maanein matrix ki size $2 \times 4$ hai (top = 0, bottom = 1, left = 0, right = 3):
- Left to Right (
row = top,col = left..right):toprow traverse hui $\rightarrow$top++(top = 1). - Top to Bottom (
row = top..bottom,col = right):rightcol traverse hua $\rightarrow$right--(right = 2). - Ab agar sirf
1row bachi ho (jaise $1 \times 4$ matrix meintoppehle hi1ho chuka ho aurbottom = 0ho), to:- Right to Left (
row = bottom,col = right..left) chalane se pehleif (top <= bottom)check na ho to woh already visited row ko ulta traverse kar dega. - Bottom to Top (
row = bottom..top,col = left) chalane se pehleif (left <= right)check na ho to woh already visited column ko neeche se oopar traverse kar dega.
- Right to Left (
Step-by-Step Boundary Rules
Initialize: top = 0, bottom = m - 1, left = 0, right = n - 1. Loop tab tak chalayein jab tak top <= bottom && left <= right:
- Left $\rightarrow$ Right:
cfromlefttorighton rowtop. Phirtop++. - Top $\rightarrow$ Bottom:
rfromtoptobottomon colright. Phirright--. - Right $\rightarrow$ Left (
if top <= bottom):cfromrightdown tolefton rowbottom. Phirbottom--. - Bottom $\rightarrow$ Top (
if left <= right):rfrombottomdown totopon colleft. Phirleft++.
Code Implementation
Python Solution
def spiral_order(matrix: list[list[int]]) -> list[int]:
if not matrix or not matrix[0]:
return []
m, n = len(matrix), len(matrix[0])
top, bottom = 0, m - 1
left, right = 0, n - 1
result: list[int] = []
while top <= bottom and left <= right:
# 1. Traverse top row from left to right
for c in range(left, right + 1):
result.append(matrix[top][c])
top += 1
# 2. Traverse right column from top to bottom
for r in range(top, bottom + 1):
result.append(matrix[r][right])
right -= 1
# 3. Traverse bottom row from right to left (only if a row remains)
if top <= bottom:
for c in range(right, left - 1, -1):
result.append(matrix[bottom][c])
bottom -= 1
# 4. Traverse left column from bottom to top (only if a column remains)
if left <= right:
for r in range(bottom, top - 1, -1):
result.append(matrix[r][left])
left += 1
return result
C++ Solution
#include <vector>
std::vector<int> spiralOrder(const std::vector<std::vector<int>>& matrix) {
if (matrix.empty() || matrix[0].empty()) {
return {};
}
int m = static_cast<int>(matrix.size());
int n = static_cast<int>(matrix[0].size());
int top = 0, bottom = m - 1;
int left = 0, right = n - 1;
std::vector<int> result;
result.reserve(static_cast<size_t>(m) * n);
while (top <= bottom && left <= right) {
// 1. Left to right across top boundary
for (int c = left; c <= right; ++c) {
result.push_back(matrix[top][c]);
}
++top;
// 2. Top to bottom down right boundary
for (int r = top; r <= bottom; ++r) {
result.push_back(matrix[r][right]);
}
--right;
// 3. Right to left across bottom boundary
if (top <= bottom) {
for (int c = right; c >= left; --c) {
result.push_back(matrix[bottom][c]);
}
--bottom;
}
// 4. Bottom to top up left boundary
if (left <= right) {
for (int r = bottom; r >= top; --r) {
result.push_back(matrix[r][left]);
}
++left;
}
}
return result;
}
Complexity
- Time Complexity: $O(m \cdot n)$ — har cell exact aik baar visit hota hai.
- Auxiliary Space: $O(1)$ — sirf four boundary pointers (
top,bottom,left,right) aur loop variables use hote hain (output list ko chhor kar).
