Given a 2D matrix of numbers, return a spiral traversal of the matrix in the clockwise direction.
matrix = [
[1, 2, 3, 4],
[12, 13, 14, 5],
[11, 16, 15, 6],
[10, 9, 8, 7],
];
[
1, 2, 3, 4,
5, 6, 7, 8,
9, 10, 11, 12,
13, 14, 15, 16
]
In the clockwise direction, we go from
1 <= matrix.length <= 1000
1 <= matrix[i][j] <= 1000
Click to reveal
Try using indexes for rows
and columns
in the matrix. There can be 4 for-loops to iterate over rows and columns. How can you make sure that you cover all the elements?
Click to reveal
Is there a recursive approach to solve this problem? Can you try using recursion to print out the boundaries of the matrix and then step into a deeper level?