Javascript Accepted


  • 0
    W
    /**
     * @param {number} n
     * @returns {number[][]}
     */
    var generateMatrix = function(n) {
        var result = [];
        var index = 0;
        for(;index < n;index++) {
        	result.push(new Array(n));
        }
        var i = 0, j = 0, directionX = 0, directionY = 1;
        index = 1;
        while(index <= Math.pow(n,2)) {
        	result[i][j] = index++;
        	if((directionX === 0 && directionY === 1) && (j === n-1 || result[i][j+1] !== undefined)){
        		directionX = 1;
        		directionY = 0;
        	}
        	else if((directionX === 1 && directionY === 0) && (i === n-1 || result[i+1][j] !== undefined)){
        		console.log('t2');
        		directionX = 0;
        		directionY = -1;
        	}
        	else if((directionX === 0 && directionY === -1) && (j === 0 || result[i][j-1] !== undefined)){
        		directionX = -1;
        		directionY = 0;
        	}
        	else if((directionX === -1 && directionY ===0) && (i === 0 || result[i-1][j] !== undefined)){
        		directionX = 0;
        		directionY = 1;
        	}
        	i += directionX;
        	j += directionY;
        }
        return result;
    };
    

    http://blog.willin.wang/posts/2015/leetcode-spiral-matrix-ii/


Log in to reply
 

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