8 line C++ solution, Real Spiral using M_PI


  • 0
    A

    Turn pi/2 clockwise every time reach a boundary

    class Solution {
    public:
    
        vector<vector<int>> generateMatrix(int n) {
            
            vector<vector<int>> matrix(n,vector<int> (n,0));
            int count = 0, i=0, j=-1, angle = 0;
    
            while(count<n*n) {
              
                int istep = (int) sin(angle*M_PI/2), jstep = (int) cos(angle*M_PI/2);
                
                if( i+istep<0 || i+istep>=n || j+jstep<0 || j+jstep>=n || matrix[i+istep][j+jstep] != 0) angle++;
    
                i += (int) sin(angle*M_PI/2);  j += (int) cos(angle*M_PI/2);
                
                matrix[i][j] = ++count;
                
            }
    
            return matrix;
        }
    };
    

Log in to reply
 

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