Problem

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

Example

Input ::
[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]
Output :: 
[1,2,3,6,9,8,7,4,5].

JavaScript Code

function spiralOrder(matrix) {
    var result = [];

    if(matrix == null || matrix.length == 0) return result;

    var m = matrix.length;
    var n = matrix[0].length;

    var x=0; 
    var y=0;

    while(m>0 && n>0){
        //if one row/column left, no circle can be formed
        if(m==1){
            for(var i=0; i<n; i++){
                result.push(matrix[x][y++]);
            }
            break;
        } else if(n==1){
            for(var i=0; i<m; i++){
                result.push(matrix[x++][y]);
            }
            break;
        }

        //below, process a circle

        //top - move right
        for(var i=0;i<n-1;i++){
            result.push(matrix[x][y++]);
        }
        //right - move down
        for(var i=0;i<m-1;i++){
            result.push(matrix[x++][y]);
        }
        //bottom - move left
        for(var i=0;i<n-1;i++){
            result.push(matrix[x][y--]);
        }
        //left - move up
        for(var i=0;i<m-1;i++){
            result.push(matrix[x--][y]);
        }
        x++;
        y++;
        m=m-2;
        n=n-2;
    }

    return result;
}

0 comments:

Blogroll

Popular Posts