Traverse a matrix in spiral order
Return the elements of a rectangular matrix in clockwise spiral order starting at the top-left corner.
Course progress
Problem 99 of 100
Example → approach → runnable solution
Worked example
See the problem in action
Trace a concrete input through to the verified result.
Example input
matrix = [[1,2,3],[4,5,6],[7,8,9]]
Expected output
1 2 3 6 9 8 7 4 5
What is happening?
Read the top row, right edge, bottom row in reverse, left edge upward, then the center: 1,2,3,6,9,8,7,4,5.
Solution strategy
Build the right mental model
Maintain top, bottom, left, and right boundaries, traversing one exposed edge at a time before shrinking that boundary.
Core concepts
matrix · boundary tracking
Complexity
Time O(rows x columns), space O(rows x columns) for the result.
Runnable solution
Learn from working code
Compare languages, copy the code, or open it in the compiler.
Complete C# solution for spiral-matrix-traversal
using System;
using System.Collections.Generic;
class Program
{
static List<int> SpiralOrder(int[,] matrix)
{
var result = new List<int>();
int top = 0, bottom = matrix.GetLength(0) - 1;
int left = 0, right = matrix.GetLength(1) - 1;
while (top <= bottom && left <= right)
{
for (int column = left; column <= right; column++) result.Add(matrix[top, column]);
top++;
for (int row = top; row <= bottom; row++) result.Add(matrix[row, right]);
right--;
if (top <= bottom)
for (int column = right; column >= left; column--) result.Add(matrix[bottom, column]);
bottom--;
if (left <= right)
for (int row = bottom; row >= top; row--) result.Add(matrix[row, left]);
left++;
}
return result;
}
static void Main()
{
int[,] matrix = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
Console.WriteLine(string.Join(" ", SpiralOrder(matrix)));
}
}Knowledge check
Questions students often ask
What is the main idea behind traverse a matrix in spiral order?
Maintain top, bottom, left, and right boundaries, traversing one exposed edge at a time before shrinking that boundary.
What is the time and space complexity of this solution?
Time O(rows x columns), space O(rows x columns) for the result.
Do all language tabs solve the same problem?
Yes. Every program uses the same example and produces the verified output shown on this page. The syntax and a few language-specific data structures differ.