Concise JavaScript O(n) using directions


  • 1
    var spiralOrder = function(matrix) {
        if (!matrix.length) return [];
        const res = [];
        let dir, dirs = [[0, 1], [1, 0], [0, -1], [-1, 0]];
        const walls = [-1, matrix[0].length, matrix.length, -1];
        for (let i = 0, d = 0, r = 0, c = 0, len = matrix.length * matrix[0].length; i < len; i++, r += dir[0], c += dir[1]) {
            res.push(matrix[r][c]);
            dir = dirs[d % 4];
            let w = [0, 1, 2, 3].find(j => j % 2 === 0 && r + dir[0] === walls[j] || j % 2 && c + dir[1] === walls[j]);
            if (w !== undefined) {
                walls[(w + 3) % 4] += w < 2 ? 1 : -1;
                dir = dirs[++d % 4];
            }
        }
        return res;
    };
    

    @stellari's solution is cleaner. Here it is in JavaScript for comparison:

    var spiralOrder = function(matrix) {
        if (!matrix.length) return [];
        const res = [];
        const dirs = [[0, 1], [1, 0], [0, -1], [-1, 0]];
        const range = [matrix[0].length, matrix.length - 1];
        let d = 0, r = 0, c = -1;
        while (range[d % 2] > 0) {
            for (let i = 0; i < range[d % 2]; i++) {
                r += dirs[d][0];
                c += dirs[d][1];
                res.push(matrix[r][c]);
            }
            range[d % 2]--;
            d = (d + 1) % 4;
        }
        return res;
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.