4ms Clear C++ Solution


  • 0

    The idea is just to generate the matrix in the spiral order. First the up-most row (u), then the right-most column (r), then the down-most row (d), and finally the left-most column (l). After generating a row or a column, update the corresponding variable to continue the generation.

    The code is as follows.

    class Solution {
    public:
        vector<vector<int> > generateMatrix(int n) { 
            vector<vector<int> > mat(n, vector<int>(n));
            int u = 0, d = n - 1, l = 0, r = n - 1, num = 1;
            while(true) {
                // up
                for(int col = l; col <= r; col++) mat[u][col] = num++;
                if(++u > d) break;
                // right
                for(int row = u; row <= d; row++) mat[row][r] = num++;
                if(--r < l) break;
                // down
                for(int col = r; col >= l; col--) mat[d][col] = num++;
                if(--d < u) break;
                // left
                for(int row = d; row >= u; row--) mat[row][l] = num++;
                if(++l > r) break;
            }
            return mat;
        }
    };

Log in to reply
 

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