Problem 337143 · medium · Phase 03 Linear Management & Searching

Spiral Fill From a List

matrix · simulation · direction vectors

Create an m x n grid and fill it with the elements of values in clockwise spiral order, starting at the top-left cell and moving right first. If values has fewer than m * n elements, the remaining cells (which are visited last in the spiral) are filled with -1. Extra elements are ignored.

Examples

Input:  m = 2, n = 3, values = [1, 2, 3, 4, 5, 6]
Output: [[1, 2, 3], [6, 5, 4]]

Input:  m = 3, n = 3, values = [1, 2, 3, 4, 5, 6, 7]
Output: [[1, 2, 3], [-1, -1, 4], [7, 6, 5]]
Explanation: the spiral runs right along row 0, down column 2, left along row 2 and then
             back up column 0; cells 8 and 9 are never reached by `values`.

Constraints

  • 1 <= m, n <= 300
  • Target: O(m * n) time.

Goals

  • Walk a grid in a clockwise spiral by turning when the next cell is out of bounds or already filled
  • Build an m x n grid of placeholders and write into it
  • Consume an iterator of values, falling back to a default when it runs dry
Starting Python…