1. var spiralOrder = function(matrix) {
    2. if (!matrix.length || !matrix[0].length) {
    3. return [];
    4. }
    5. const rows = matrix.length, columns = matrix[0].length;
    6. const visited = new Array(rows).fill(0).map(() => new Array(columns).fill(false));
    7. const total = rows * columns;
    8. const order = new Array(total).fill(0);
    9. let directionIndex = 0, row = 0, column = 0;
    10. const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]];
    11. for (let i = 0; i < total; i++) {
    12. order[i] = matrix[row][column];
    13. visited[row][column] = true;
    14. const nextRow = row + directions[directionIndex][0], nextColumn = column + directions[directionIndex][1];
    15. if (!(0 <= nextRow && nextRow < rows && 0 <= nextColumn && nextColumn < columns && !(visited[nextRow][nextColumn]))) {
    16. directionIndex = (directionIndex + 1) % 4;
    17. }
    18. row += directions[directionIndex][0];
    19. column += directions[directionIndex][1];
    20. }
    21. return order;
    22. };