C++ template for Spiral Matrix & Spiral Matrix II


  • 3

    Spiral Matrix II code:

    class Solution {
    public:
        vector<vector<int>> generateMatrix(int n) {
            vector<vector<int>> result(n, vector<int>(n, 0));
            int l=0, r=n-1, u=0, d=n-1;
            int k=1;
            while(true){
                for(int i=l; i<=r; i++)  result[u][i]=k++;
                if(++u>d) break;
                
                for(int i=u; i<=d; i++)  result[i][r]=k++;
                if(r--<l) break;
                
                for(int i=r; i>=l; i--)  result[d][i]=k++;
                if(--d<u) break;
                
                for(int i=d; i>=u; i--)  result[i][l]=k++;
                if(++l>r) break;
            }
            return result;
        }
    };
    

    Spiral Matrix Code:

    class Solution {
    public:
        vector<int> spiralOrder(vector<vector<int>>& matrix) {
            if(matrix.empty())  return {};
            int m=matrix.size(), n=matrix[0].size();
            vector<int> spiral(m*n);
            int u=0, d=m-1, l=0, r=n-1, k=0;
            while(true){
                /** up **/
                for(int col=l; col<=r; col++)  spiral[k++]=matrix[u][col];
                if(++u>d) break;
                /** right **/
                for(int row=u; row<=d; row++)  spiral[k++]=matrix[row][r];
                if(--r<l) break;
                /** down **/
                for(int col=r; col>=l; col--)  spiral[k++]=matrix[d][col];
                if(--d<u) break;
                /** left **/
                for(int row=d; row>=u; row--)  spiral[k++]=matrix[row][l];
                if(++l>r) break;
            }
            return spiral;
        }
    };

Log in to reply
 

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