Posted on

Description

Submission

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int>> res(n, vector<int>(n, -1));
        
        vector<vector<int>> dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
        
        int nDir = 0;
        for(int i = 0, j = 0, k = 1, total = n * n; k <= total; 
            i += dirs[nDir][0], j += dirs[nDir][1], k++) {
            res[i][j] = k;
            
            int nextI = i + dirs[nDir][0];
            int nextJ = j + dirs[nDir][1];
            if(nextI >= n || nextJ >= n || nextI < 0 || nextJ < 0
              || res[nextI][nextJ] != -1) {
                nDir = (nDir + 1) % 4;
            }
        }
        
        return res;
        
    }
};

Leave a Reply

Your email address will not be published. Required fields are marked *