Skip to content
RED SAGSkills
medium30 ptsmatrixsimulation

Spiral Walk of a Grid

Return all values of a rectangular grid in clockwise spiral order, starting at the top-left cell and moving right first.

Example 1

Input: grid = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1, 2, 3, 6, 9, 8, 7, 4, 5]

Example 2

Input: grid = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
Output: [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]

Constraints

  • 0 <= rows, cols <= 200
  • All rows have the same length.
Hint 1

Keep four boundaries: top, bottom, left and right.

Hint 2

Walk one ring at a time and watch out for a single remaining row or column.

Discussion 0

Join free to post in the discussion.

Good practice for: Frontend Developer, Backend Developer, Full Stack Developer, Mobile App Developer, Automation Test Engineer, Game Developer

Run checks your code on 2 sample tests. Submit runs all 8 tests, including hidden ones, and earns points. Use console.log to debug. Python's first run can take a few seconds while it starts.