Skip to content

leetcode59: 不用定义那么多复杂的变量。只用一个start和end就能解决 #2893

Open
@Hitoku08

Description

@Hitoku08
public:
    vector<vector<int>> generateMatrix(int n) {
        // Be careful on the boundary conditions
        int start = 0, end = n - 1;
        int x = 1;
        // 2D vector should be initialized correctly!!!
        vector<vector<int>> mat(n, vector<int>(n));
        while (start<=end) {
            int i = start, j = start;
            while (j < end) {
                mat[i][j++] = x++;
            }
            while (i < end) {
                mat[i++][j] = x++;
            }
            while (j > start) {
                mat[i][j--] = x++;
            }
            while (i > start) {
                mat[i--][j] = x++;
            }
            start++;
            end--;
        }
        // if n is odd
        if (n % 2) {
            mat[n / 2][n / 2] = x;
        }
        return mat;
    }
};

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions