iterate over matrix in spiral in javascript

To iterate over a matrix in a spiral order, we can use the concept of layers. We start by traversing the outermost layer of the matrix in a clockwise direction, and then move towards the center of the matrix by traversing the inner layers in a similar fashion. Here's an implementation of this algorithm in JavaScript:

index.tsx
function spiralTraversal(matrix) {
  let rows = matrix.length;
  let cols = matrix[0].length;
  let visited = new Array(rows).fill().map(() => new Array(cols).fill(false)); // Create a visited matrix

  let result = [];
  let row = 0;
  let col = 0;
  let dir = "right";

  // Define the boundaries of the matrix
  let topBoundary = 0;
  let bottomBoundary = rows - 1;
  let leftBoundary = 0;
  let rightBoundary = cols - 1;

  // Loop through all the elements in the matrix
  for (let i = 0; i < rows * cols; i++) {
    // Mark current cell as visited
    visited[row][col] = true;
    result.push(matrix[row][col]);

    // Move in the appropriate direction
    if (dir === "right") {
      if (col === rightBoundary) {
        dir = "down";
        topBoundary++;
        row++;
      } else {
        col++;
      }
    } else if (dir === "down") {
      if (row === bottomBoundary) {
        dir = "left";
        rightBoundary--;
        col--;
      } else {
        row++;
      }
    } else if (dir === "left") {
      if (col === leftBoundary) {
        dir = "up";
        bottomBoundary--;
        row--;
      } else {
        col--;
      }
    } else if (dir === "up") {
      if (row === topBoundary) {
        dir = "right";
        leftBoundary++;
        col++;
      } else {
        row--;
      }
    }
  }

  return result;
}
1349 chars
61 lines

To use this function, simply call it with a matrix as an argument:

index.tsx
const matrix = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
];

console.log(spiralTraversal(matrix));
// Output: [1, 2, 3, 6, 9, 8, 7, 4, 5]
137 chars
9 lines

gistlibby LogSnag