Q5: How do you traverse an M x N 2D matrix in Spiral Order?
Maintain four boundary boundaries: top, bottom, left, and right. Traverse right along top, down along right, left along bottom (if top <= bottom), and up along left (if left <= right), shrinking boundaries inward after each direction traversal.
Spiral Matrix Traversal
import java.util.*;
public class SpiralMatrix {
public static List<Integer> spiralOrder(int[][] matrix) {
List<Integer> result = new ArrayList<>();
if (matrix == null || matrix.length == 0) return result;
int top = 0, bottom = matrix.length - 1;
int left = 0, right = matrix[0].length - 1;
while (top <= bottom && left <= right) {
for (int col = left; col <= right; col++) result.add(matrix[top][col]);
top++;
for (int row = top; row <= bottom; row++) result.add(matrix[row][right]);
right--;
if (top <= bottom) {
for (int col = right; col >= left; col--) result.add(matrix[bottom][col]);
bottom--;
}
if (left <= right) {
for (int row = bottom; row >= top; row--) result.add(matrix[row][left]);
left++;
}
}
return result;
}
}💡 Scans grid perimeters clockwise while shrinking boundary limits.
Key Takeaways
- Track four dynamic boundary boundaries.
- Shrink boundaries inward and verify non-overlapping conditions before scanning reverse directions.
Knowledge Check
Why are the checks top <= bottom and left <= right required inside the spiral loop before processing bottom and left sweeps?