Travesal matrix in a spiral form

Design an algorithm to traverse and print all elements of a given m x n matrix in a spiral order, starting from the top-left corner and moving clockwise.

Hint

We'll work with the edges of each layer: top, right, bottom, and left. Start at the top edge (left to right), move to the right edge (top to bottom), bottom (right to left), and left (bottom to top). Repeat this process for every layer of the matrix, working your way inwards.

# Python implementation
matrix = [
  [ 1, 2, -1, -4, -20 ],
  [ -8, -3, 4, 2, 1 ],
  [ 3, 8, 10, 1, 3 ],
  [ -4, -1, 1, 7, -6 ]
]
output = []
h = len(matrix)
w = len(matrix[0])
top = 0
bottom = h - 1
left = 0
right = w - 1

while (top <= bottom and left <= right):
  for i in range(left, right + 1):
    output.append(matrix[top][i])
  
  top += 1
  
  for i in range(top, bottom + 1):
    output.append(matrix[i][right])
  
  right -= 1

  if top <= bottom:
    for i in range(right, left - 1):
      output.append(matrix[bottom][i])

    bottom -= 1
  
  if left <= right:
    for i in range(bottom, top - 1):
      output.append(matrix[i][left])

    left += 1

print(output)
// Javascript implementation
const matrix = [
  [ 1, 2, -1, -4, -20 ],
  [ -8, -3, 4, 2, 1 ],
  [ 3, 8, 10, 1, 3 ],
  [ -4, -1, 1, 7, -6 ]
];
const output = []
const h = matrix.length;
const w = matrix[0].length;
let top = 0, bottom = h - 1, left = 0, right = w - 1;

while (top <= bottom && left <= right) {
  for (let i = left; i <= right; ++i) {
    output.push(matrix[top][i]);
  }
  top++;
  
  for (let i = top; i <= bottom; ++i) {
    output.push(matrix[i][right]);
  }
  right--;

  if (top <= bottom) {
    for (let i = right; i >= left; --i) {
      output.push(matrix[bottom][i]);
    }
    bottom--;
  }
  
  if (left <= right) {
    for (let i = bottom; i >= top; --i) {
      output.push(matrix[i][left]);
    }
    left++;
  }
}

console.log(output);