My c++ straightforward solution


  • 0
    class Solution {
    public:
        vector<vector<int>> generateMatrix(int n) {
            int a[n][n];
            int start_row = 0, start_col = 0, end_row = n - 1, end_col = n - 1;
            if (n == 0) return {};
            if (n == 1) return {{1}};
            int i = 1;
            while (i <= n * n){
                // Fill the number along the edge of the matrix 
                for (int j = start_col; j <= end_col && i <= n*n; ++j) {
                    a[start_row][j] = i++;
                }
                // Since a[start_row][end_col] is set, start from a[start_row+1][end_col]
                for (int j = start_row + 1; j <= end_row && i <= n*n; ++j) {
                    a[j][end_col] = i++;
                }
                // Same as the above, but for the column
                for (int j = end_col - 1; j >= start_col && i <= n*n; --j) {
                    a[end_row][j] = i++;
                }
                // a[start_row][start_col] and a[end_row][start_col] has been set, so the range of this should be within [start_row + 1, end_row - 1]
                for (int j = end_row - 1; j >= start_row + 1 && i <= n*n; --j) {
                    a[j][start_col] = i++;
                }
                // When we complete filling the numbers in on the edge of the matrix, reduce the edge
                start_row += 1;
                end_row -= 1;
                start_col += 1;
                end_col -= 1;
            }
            vector<vector<int>> result(n, vector<int>(n,0));
            for (int i = 0; i < n; ++i) {
                for (int j = 0; j < n; ++j) {
                    result[i][j] = a[i][j];
                } 
            } 
            return result;
        }
            
    };

  • 0

    @LinHungShi Man, you are just making fun around here :beers: if you want it simple you actually can merge the loops altogether like this

    class Solution {
    public:
        vector<vector<int>> generateMatrix(int n) 
        {
            if(!n) return vector<vector<int>>();
            vector<vector<int>> vv(n, vector<int>(n));
            int dirs[][2]{{0,1}, {1,0}, {0,-1}, {-1,0}};
            int steps[2]{n, n-1};
            int r = 0, c = -1, i = 0, a = 1;
            while(steps[i%2])
            {
                for(int j = 0; j < steps[i%2]; ++j)
                {
                    r += dirs[i][0], c += dirs[i][1];
                    vv[r][c] = a++;
                }
                steps[i%2]--;
                i = (i+1)%4;
            }
            return vv;
        }
    };
    

  • 0

    @LHearen Though not so straightforward to me, it's a smart trick and makes the code more concise, thank you.


Log in to reply
 

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