my C++ solution for spiral matrix and explanation


  • 0
    2

    0_1474797032333_upload-5fbf2a03-8c62-4237-befb-e80b8d3e1808

    class Solution {
        void spiral(vector<vector<int>>& matrix,vector<int> & r, int i, int j, int k, int l)
        {
            if(i>k||j>l)
            return;
            if(i==k)
            for(int p=j;p<=l;p++)//only one row
            r.push_back(matrix[i][p]);
            else if(j==l)
            for(int p=i;p<=k;p++)//only one col
            r.push_back(matrix[p][j]);
            else
            {
            for(int p=j;p<=l;p++)//traverse right
            r.push_back(matrix[i][p]);
            for(int p=i+1;p<=k;p++)//traverse down
            r.push_back(matrix[p][l]);
            for(int p=l-1;p>=j;p--)//traverse left
            r.push_back(matrix[k][p]);
            for(int p=k-1;p>i;p--)//traverse up
            r.push_back(matrix[p][j]);
            spiral(matrix,r,i+1,j+1,k-1,l-1);
            }
            
        }
    public:
        vector<int> spiralOrder(vector<vector<int>>& matrix) {
            vector<int> r;
            int m=matrix.size();
            if(m==0)
            return r;
            int n=matrix[0].size();
            spiral(matrix,r,0,0,m-1,n-1);
            return r;
            
        }
    };
    

Log in to reply
 

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