Simple C++ solution based on direction


  • 0
    L

    Just use direction to mimic the natural logic.

    class Solution {
    public:
        vector<vector<int>> generateMatrix(int n) {
          
          vector<vector<int>> res(n, vector<int>(n,0));
          
          vector<vector<int>> dirs = {{0,1}, {1,0}, {0,-1}, {-1,0}} ;
          
          vector<int> steps{n,n-1};
          
          int m=0;
          int x=0, y=-1;
          int i=0; //direction
          
          int seq = 1;
          while ( m = steps[i%2])
          {
              while (m--)
              {
                  x += dirs[i][0];
                  y += dirs[i][1];
                  
                  res[x][y] = seq++;
              }
              
              steps[i%2]--;
              i = (i+1)%4;
          }
          
          return res;
        }
    };
    

Log in to reply
 

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