My Javascript Solution


  • 0
    R
    /**
     * @param {number} n
     * @return {number[][]}
     */
    var generateMatrix = function(n) {
      var matrix = [];
      for(var i = 0; i < n; i++){
        var row = [];
        for(var j = 0; j < n; j++){
          row.push(0);
        }
        matrix.push(row);
      }
      var count = 1;
    
      for(var i = 0; i < n; i++){
        
        //first row left
        for(var j = 0 + i; j < n - 1 - i; j++){
          matrix[i][j] = count;
          count ++;
        }
        //far right row down
        for(var j = i; j < n - i; j++){
          matrix[j][n - 1 - i] = count;
          count ++;
        }
        //Bottom row left
        for(var j = n - 2 - i; j >= 0 + i; j--){
          matrix[n - 1 - i][j] = count;
          count ++;
        }    
        //Bottom row up
        for(var j = n - 2 - i; j >= 1 + i; j--){
          matrix[j][i] = count;
          count ++;
        }
    
      }
    
      return matrix;    
    };
    

Log in to reply
 

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