All problems
Spiral Matrix Generation
Problem
Generate an n by n matrix filled with the numbers 1 to n squared in clockwise spiral order starting at the top-left corner.
Maintain top, bottom, left and right boundaries, walking each side and shrinking that boundary after every pass. Return an empty list for n <= 0.
Hint
After each side, move its boundary inward; guard the last row and column when the center is reached.
Test cases
case 1
in: [1]
expected: [[1]]
case 2
in: [2]
expected: [[1,2],[4,3]]
case 3
in: [3]
expected: [[1,2,3],[8,9,4],[7,6,5]]
case 4
in: [0]
expected: []
Starter codePython
def generate_spiral_matrix(n):
# Your code here
pass4 test cases · run your code against them in the editor