4ms simple c++ solution with comments


  • 0
    H
    class Solution {
    public:
      vector<vector<int>> generateMatrix(int n) {
      vector<vector<int>> res(n,vector<int>(n,0));
      int curLayer = 0; //indicates what circular layer its operating
      int idx = 1;
      int curRow;
      int curCol;
      
       while(1)  
      {
          curRow = curLayer;
          for(int col = curLayer; col < n - curLayer; col++) //top row
          {
              res[curRow][col] = idx++;
          }
          curCol = n - curLayer - 1;
          for(int row = curLayer+1; row < n - curLayer; row++) //last column
          {
              res[row][curCol] = idx++;
          }
          curRow = n - curLayer -1;
          for(int col = n - curLayer-2; col >= curLayer; col--) //bottom row
          {
              res[curRow][col] = idx++;
          }
          curCol = curLayer;
          for(int row = n - curLayer-2; row > curLayer; row--)//first column
          {
              res[row][curCol] = idx++;
          }
          curLayer++;
          if((n+1)/2 == (curLayer)) //the number of spiral layer is half the n
          {
              break;
          }          
      }
      
      return res;
        
    }
    };

Log in to reply
 

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