My c++ solution easy to understand


  • 0
    I
    void help(vector<vector<int>>& matrix, int i, int j, int dir, int val) {
        int n = matrix.size();
        if (n * n == val) {
            matrix[i][j] = val;
            return;
        }
        n = n - 1;
        switch (dir) {
            case 0:
                for (int k = j; k < n - j; k++) matrix[i][k] = val++;
                help(matrix, i, n - j, dir + 1, val);
                break;
            case 1:
                for (int k = i; k < n - i; k++) matrix[k][j] = val++;
                help(matrix, n - i, j, dir + 1, val);
                break;
            case 2:
                for (int k = j; k > n - j; k--) matrix[i][k] = val++;
                help(matrix, i, n - j, dir + 1, val);
                break;
            case 3:
                for (int k = i; k > n - i; k--) matrix[k][j] = val++;
                help(matrix, n - i + 1, j + 1, 0, val);
                break;
        }
    }
    
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int>> spiral_matrix(n, vector<int>(n, 1));
        if (n == 0) return spiral_matrix;
        help(spiral_matrix, 0, 0, 0, 1);
        return spiral_matrix;
    }

Log in to reply
 

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