Easy solution 0ms in C++ with meaningful notations for variables


  • 1
    J

    #define pb push_back

    class Solution {
    public:
    vector<int> spiralOrder(vector<vector<int> >& m) {
    vector<int> ans;
    int row = m.size();
    if(!row)
    return ans;
    int col = m[0].size();

        int startx, starty, endx, endy;
        startx = starty = 0;
        endx = col - 1;
        endy = row - 1;
        
        if( !row && !col )
            return ans;
        
        while ( startx <= endx && starty <= endy ) {
            for (int i=startx ; i <= endx ; i++) {
                ans.pb(m[starty][i]);
            }
            starty++;
            for (int i= starty ; i <= endy ; i++ ) {
                ans.pb(m[i][endx]);
            }
            endx--;
            if ( starty <= endy ) {
                for ( int i = endx ; i >= startx; i--) {
                    ans.pb(m[endy][i]);
                }
                endy--;
            }
            if ( startx <= endx ) {
                for ( int i = endy ; i >= starty ; i-- ) {
                    ans.pb(m[i][startx]);
                }
                startx++;
            }
        }
        return ans;
    }
    

    };
    enter code here


Log in to reply
 

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