Clean C++ solution with comments


  • 0
    J
    class Solution {
    public:
        enum Dir { left, right, up, down }; // travel direction
    
        vector<int> spiralOrder(vector<vector<int>>& matrix) {
            vector<int> result;
            int m = matrix.size();
            if (m==0) return result;
            int n = matrix[0].size();
            if (n==0) return result;
            
            // travel bounds (inclusive)
            int LeftB = 0;
            int RightB = n-1;
            int UpB = 0;
            int LowB = m-1;
            Dir dir = right;
            
            int i, j;
            while(true)
            {
                // 4-state machine
                switch(dir)
                {
                    case right:
                        i = UpB;
                        for (j=LeftB; j<=RightB; j++)
                            result.push_back(matrix[i][j]);
                        UpB++;
                        dir = down;
                        break;
                    case down:
                        j = RightB;
                        for (i=UpB; i<=LowB; i++)
                            result.push_back(matrix[i][j]);
                        RightB--;
                        dir = left;
                        break;            
                    case left:
                        i = LowB;
                        for (j=RightB; j>=LeftB; j--)
                            result.push_back(matrix[i][j]);
                        LowB--;
                        dir = up;
                        break;
                    case up:
                        j = LeftB;
                        for (i=LowB; i>=UpB; i--)
                            result.push_back(matrix[i][j]);
                        LeftB++;
                        dir = right;
                        break;         
                }
                
                // Terminate if next move is not feasible
                if ((dir==left || dir==right) && LeftB>RightB) break;
                if ((dir==up || dir==down) && UpB>LowB) break;
            }
            
            return result;
        }
    };

Log in to reply
 

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