Solution with JavaScript


  • 0
    Z
    var spiralOrder = function(matrix) {
        var res = [];
        var m = matrix.length,n = m ? matrix[0].length : 0,total = m * n;
        var dir_arr = [[0,1],[1,0],[0,-1],[-1,0]],cur_dir = 0;
        var cur_x = 0,cur_y = 0;
        while (total--) {
            res.push(matrix[cur_x][cur_y]);
            matrix[cur_x][cur_y] = false;
            cur_x += dir_arr[cur_dir][0];
            cur_y += dir_arr[cur_dir][1];
            if (matrix[cur_x] === undefined || matrix[cur_x][cur_y] === undefined || matrix[cur_x][cur_y] === false) {
                cur_x -= dir_arr[cur_dir][0];
                cur_y -= dir_arr[cur_dir][1];
                cur_dir++;
                if (!dir_arr[cur_dir]) {
                    cur_dir = 0;
                }
                cur_x += dir_arr[cur_dir][0];
                cur_y += dir_arr[cur_dir][1];
            }
        }
        return res;
    };
    

Log in to reply
 

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