Print boundary elements of a matrix

Given an n x m matrix, write an algorithm to print all the elements that lie on its outer edges. These include the elements in the first row, the last row, the first column, and the last column of the matrix.

Hint

Create an empty list to record the order in which the algorithm will visit positions. Start at the top-right corner of the matrix. Move along the top row from right to left, then down the rightmost column. Move along the bottom row from right to left, then up the leftmost column. Avoid adding a corner twice when moving between edges. As the algorithm moves around the boundary, it adds each visited position to the list of steps.

# Python implementation
matrix = [
  [5, 1, 3, 4, 1],
  [6, 9, 6, 5, 1],
  [5, 3, 3, 7, 1],
  [1, 9, 6, 5, 3]
]
output = []
h = len(matrix)
w = len(matrix[0])

for i in range(w):
  output.append(matrix[0][i])

for i in range(1, h):
  output.append(matrix[i][w - 1])

for i in range(w - 2, -1, -1):
  output.append(matrix[h-1][i])

for i in range(h - 2, 0, -1):
  output.append(matrix[i][0])

print(output)
// Javascript implementation
const matrix = [
  [5, 1, 3, 4, 1],
  [6, 9, 6, 5, 1],
  [5, 3, 3, 7, 1],
  [1, 9, 6, 5, 3]
];
const output = [];
const h = matrix.length;
const w = matrix[0].length;

for (let i = 0; i < w; i++) {
  output.push(matrix[0][i]);
}

for (let i = 1; i < h; i++) {
  output.push(matrix[i][w - 1]);
}

for (let i = w - 2; i >= 0; i--) {
  output.push(matrix[h-1][i]);
}

for (let i = h - 2; i >= 1; i--) {
  output.push(matrix[i][0]);
}

console.log(output);