Simple and easy understanding c++ solution, go through each circle


  • 0
    C
    class Solution {
    public:
        vector<vector<int>> generateMatrix(int n) {
            if (n == 0) return vector<vector<int>>();
            vector<vector<int>> result(n, vector<int>(n, 0));
            int count = n/2, num = 1;
            for (int k = 0; k < count; k++) {
                for (int i = 0; i < n - 2*k; ++i)
                    result[k][k + i] = num++;
                for (int i = 1; i < n - 2*k; ++i)
                    result[k + i][n - 1 - k] = num++;
                for (int i = 1; i < n - 2*k; ++i)
                    result[n - 1 - k][n - 1 - k - i] = num++;
                for (int i = 1; i < n - 2*k - 1; ++i)
                    result[n - 1 - k - i][k] = num++;
            }
            if (n & 1)
                result[n/2][n/2] = num;
            return result;
        }
    };

Log in to reply
 

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