Start learning free

LESSON 301 OF 639 · MATRIX

Spiral Matrix II in Go

Practice O(n²)

You get an integer n.

Return a square grid with n rows and n columns. It holds the numbers from 1 to n2, laid out in a spiral.

1 goes in the top-left cell. Each next number goes in the next cell of the spiral.

The spiral goes clockwise around the edge. It goes right along the top row, then down the right column. Then it goes left along the bottom row and up the left column.

Next, it does the same with the smaller grid inside, until every cell has a number.

Return the grid as an array of rows. Each row is an array of integers. Row 0 is the top row.

 

Example 1:

Input: n = 4
Output: [
  [1, 2, 3, 4],
  [12, 13, 14, 5],
  [11, 16, 15, 6],
  [10, 9, 8, 7]
]
Explanation: The edge gets the numbers 1 to 12:
1 to 4 across the top,
5 to 7 down the right side,
8 to 10 back along the bottom,
11 and 12 up the left side.
The 2 by 2 grid inside gets 13 to 16.

Example 2:

Input: n = 2
Output: [
  [1, 2],
  [4, 3]
]
Explanation: 1 and 2 fill the top row.
3 goes below the 2.
4 goes to the left of the 3.

Example 3:

Input: n = 5
Output: [
  [1, 2, 3, 4, 5],
  [16, 17, 18, 19, 6],
  [15, 24, 25, 20, 7],
  [14, 23, 22, 21, 8],
  [13, 12, 11, 10, 9]
]
Explanation: The edge gets the numbers 1 to 16.
The 3 by 3 grid inside gets 17 to 24 around its edge.
The last number, 25, is in the center.

 

Constraints:

  • n is from 1 to 300.

Note:

Your solution should run in O(n2) time.

STEP 1 OF 20
    Ctrl + Enter to check

    Spiral Matrix Ii in Go

    Keep going with Go500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free