Problem

Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. 

Example

Given n = 4,

[
[1,   2,  3, 4], 
[12, 13, 14, 5], 
[11, 16, 15, 6], 
[10,  9,  8, 7]
]

JavaScript Code

function generateMatrix(n) {
    var total = n*n;
    var result= [];
 
    for(var i=0;i<n;i++) {
        var rs = [];
        for(var j=0;j<n;j++) {
            rs.push(0);
        }   
        result.push(rs);
    }
    
    var x=0;
    var y=0;
    var step = 0;
    for(var i=0;i<total;){
        while(y+step<n){
            i++;
            result[x][y]=i; 
            y++;
 
        }    
        y--;
        x++;
        
        while(x+step<n){
            i++;
            result[x][y]=i;
            x++;
        }
        x--;
        y--;
         
        while(y>=step){
            i++;
            result[x][y]=i;
            y--;
        }
        y++;
        x--;
        step++;
         
        while(x>=step){
            i++;
            result[x][y]=i;
            x--;
        }
        x++;
        y++;
    }
    return result;
}

1 comment:

  1. Hello, could I possibly use this code for my arts project? Thanks

    ReplyDelete

Blogroll

Popular Posts