Return elements of an m x n matrix in spiral order.
Input: matrix=[[1,2,3],[4,5,6],[7,8,9]] → Output: [1,2,3,6,9,8,7,4,5]
Input: matrix=[[1,2,3,4],[5,6,7,8],[9,10,11,12]] → Output: [1,2,3,4,8,12,11,10,9,5,6,7]
Simulate spiral traversal using boundaries that shrink after each direction pass.
- Maintain top, bottom, left, right boundaries
- Traverse: left to right (top row), top to bottom (right col), right to left (bottom row), bottom to top (left col)
- Shrink boundaries after each pass
- Stop when boundaries cross
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res = new ArrayList<>();
int top = 0, bottom = matrix.length - 1, left = 0, right = matrix[0].length - 1;
while (top <= bottom && left <= right) {
for (int c = left; c <= right; c++) res.add(matrix[top][c]);
top++;
for (int r = top; r <= bottom; r++) res.add(matrix[r][right]);
right--;
if (top <= bottom) {
for (int c = right; c >= left; c--) res.add(matrix[bottom][c]);
bottom--;
}
if (left <= right) {
for (int r = bottom; r >= top; r--) res.add(matrix[r][left]);
left++;
}
}
return res;
}
- Time Complexity: O(m*n)
- Space Complexity: O(1)