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).
You can traverse a matrix in spiral order by using four variables:
top,bottom,left, andright.These variables help you keep track of the matrix boundaries. After visiting each row or column, move the boundary inward.
1. What Is Spiral Order?
Spiral order means visiting all elements of a matrix in a spiral shape, starting from the top-left corner.
For example:
matrix = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12] ]The spiral order will be:
2. Python Solution
Here is a simple way to solve this problem:
def spiral_order(matrix): if not matrix or not matrix[0]: return [] top = 0 bottom = len(matrix) - 1 left = 0 right = len(matrix[0]) - 1 result = [] while top <= bottom and left <= right: # Move from left to right for col in range(left, right + 1): result.append(matrix[top][col]) top += 1 # Move from top to bottom for row in range(top, bottom + 1): result.append(matrix[row][right]) right -= 1 # Move from right to left if top <= bottom: for col in range(right, left - 1, -1): result.append(matrix[bottom][col]) bottom -= 1 # Move from bottom to top if left <= right: for row in range(bottom, top - 1, -1): result.append(matrix[row][left]) left += 1 return result matrix = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12] ] print(spiral_order(matrix))Output:
3. Why Do We Use Four Boundaries?
Each variable controls one side of the matrix:
top: First row.bottom: Last row.left: First column.right: Last column.After visiting a row or column, we move its boundary inward.
We also use
ifconditions before visiting the bottom row and left column. These conditions prevent visiting the same elements twice.4. Time and Space Complexity
Conclusion
The easiest way to avoid boundary errors is to update the four boundaries after each traversal and check whether rows or columns are still available.
This approach works for both square and rectangular matrices.