Recursion problem Snail Trail in JavaScript

The snail trail problem involves traversing a 2D array in a spiral pattern from outside to inside. Given a square matrix, we need to create a flat array by following the spiral path: right ? down ? left ? up, repeating until we reach the center.

Suppose, we have an array like this:

const arr = [
  [1, 2, 3, 4],
  [12,13,14,5],
  [11,16,15,6],
  [10,9, 8, 7]
];

The array is bound to be a square matrix. We are required to write a JavaScript function that takes in this array and constructs a new array by taking elements and spiraling in until it converges to center. A snail trail spiraling around the outside of the matrix and inwards.

Therefore, the output for the above array should be:

const output = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];

Visual Representation

1 2 3 4 12 13 14 5 11 16 15 6 10 9 8 7 Spiral Path: 1. Right: 1?2?3?4 2. Down: 4?5?6?7 3. Left: 7?8?9?10 4. Up: 10?11?12 5. Right: 12?13?14 6. Down: 14?15?16

Recursive Solution

We will solve this problem using recursion. The key insight is to take the first row, then rotate the remaining matrix 90 degrees counterclockwise and repeat:

const arr = [
  [1, 2, 3, 4],
  [12,13,14,5],
  [11,16,15,6],
  [10,9, 8, 7]
];

const spiralForm = arr => {
  return arr.length > 1 ?
    arr.splice(0,1)[0]
    .concat(spiralForm(arr[0].map((c, i) => {
      return arr.map(r => r[i]);
    })
    .reverse())) :
    arr[0]
}

console.log(spiralForm(arr));
[
  1,  2,  3,  4,  5,  6,
  7,  8,  9, 10, 11, 12,
 13, 14, 15, 16
]

How It Works

The algorithm works by:

  • Base case: If only one row remains, return it
  • Recursive case: Take the first row, then transpose and reverse the remaining matrix to rotate it 90° counterclockwise
  • Matrix rotation: arr[0].map((c, i) => arr.map(r => r[i])).reverse() transposes then reverses rows

Step-by-Step Execution

// Step 1: Take first row [1,2,3,4]
// Remaining matrix after rotation:
console.log("After first iteration:");
let step1 = [[12,13,14,5], [11,16,15,6], [10,9,8,7]];
console.log("Rotated:", step1[0].map((c,i) => step1.map(r => r[i])).reverse());

// This continues recursively until convergence
After first iteration:
Rotated: [ [ 5, 6, 7 ], [ 14, 15, 8 ], [ 13, 16, 9 ], [ 12, 11, 10 ] ]

Conclusion

The recursive snail trail solution elegantly handles spiral traversal by combining row extraction with matrix rotation. Each recursive call processes one "layer" of the spiral until reaching the center.

Updated on: 2026-03-15T23:18:59+05:30

208 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements