C++ Solution with direction offsets


  • 0
    class Solution {
    public:
        vector<vector<int>> generateMatrix(int n) {
            vector<vector<int>> matrix(n,vector<int>(n));
            vector<int> ini={n,n-1};
            vector<vector<int>> offset={{0,1},{1,0},{0,-1},{-1,0}};
            int dir=0,num=0;
            int row=0,col=-1;
            while(num<n*n){
                for(int i=0;i<ini[dir%2];++i){
                    row+=offset[dir][0];
                    col+=offset[dir][1];
                    matrix[row][col]=++num;
                }
                --ini[dir%2];
                dir=(dir+1)%4;
            }
            return matrix;
        }
    };
    

Log in to reply
 

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