Clean C++ solution :O


  • 0
    I
    class Solution {
    public:
        vector<vector<int>> generateMatrix(int n) {
            vector<vector<int>> res (n, vector<int>(n));
            int layer = n / 2;
            int count = 1;
            for (int i = 0; i < layer; i++) {
                for (int j = i; j < n - 1 - i; j++) res[i][j] = count++;
                for (int j = i; j < n - 1 - i; j++) res[j][n - 1 - i] = count++;
                for (int j = n - 1 - i; j > i; j--) res[n - 1 - i][j] = count++;
                for (int j = n - 1 - i; j > i; j--) res[j][i] = count++;
            }
            if (n % 2 == 1) {
                res[n / 2][n / 2] = count;
            }
            return res;
        }
    };
    

Log in to reply
 

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