Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
Hitoku08 opened this issue Feb 12, 2025 · 0 comments

Comments

@Hitoku08
Copy link

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;
    }
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant