youngyangyang04/leetcode-master

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

Opened this issue · 0 comments

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;
    }
};