My Clean C++ code


  • 0
    Y
    class Solution {
    public:
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int>> ans;
        for (int i = 0; i < n; i++) {
            ans.push_back(vector<int>(n));
        }
        int cur = 1;
        for (int i = n; i > 0; i -= 2) {
            int l = (n - i) / 2;
            if (i == 1) {
                ans[l][l] = cur;
                break;
            }
            for (int j = 0; j < i - 1; j++) {
                ans[l][l + j] = cur++;
                ans[l + j][n - 1 - l] = ans[l][l + j] + i - 1;
                ans[n - 1 - l][n - 1 - l - j] = ans[l + j][n - 1 - l] + i - 1;
                ans[n - 1 - l - j][l] = ans[n - 1 - l][n - 1 - l - j] + i - 1;
            }
            cur += 3 * i - 3;
        }
        return ans;
    }
    };

Log in to reply
 

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