Learn
Exam

Snail Traversal

Difficulty
BEGINNER

Problem

Given a natural number n, write a function solution that returns an n x n two-dimensional array filled with numbers from 1 to n2n^2 in a snail traversal order.

The snail traversal follows these steps:

  1. Start from the top-left corner of the two-dimensional array. The number starts at 1, and the initial direction is right.
  2. Fill the current cell with the number and move one step in the current direction.
  3. If the moved cell is out of bounds or already filled with another number, return to the original cell, rotate the direction 90 degrees clockwise, and move one step.
  4. Repeat steps 2 and 3 until all cells in the two-dimensional array are filled.

For example, when n=5, the two-dimensional array filled in snail traversal order looks as follows:


Constraints

  • n is a natural number between 2 and 100 inclusive.

Test Case

Test Case Number n return
1 5 [[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]]
2 4 [[1,2,3,4],[12,13,14,5],[11,16,15,6],[10,9,8,7]]
3 7 [[1,2,3,4,5,6,7],[24,25,26,27,28,29,8],[23,40,41,42,43,30,9],[22,39,48,49,44,31,10],[21,38,47,46,45,32,11],[20,37,36,35,34,33,12],[19,18,17,16,15,14,13]]

Explanation for Test Case 1

  • This is identical to the example provided in the problem.

Explanation for Test Case 2

  • For n=4, the snail traversal fills the two-dimensional array as follows:

Explanation for Test Case 3

  • For n=7, the snail traversal fills the two-dimensional array as follows: