C++ 0ms very straightforward solution using direction


  • 2
    W
    enum Direction
    {
        LEFT,
        RIGHT,
        UP,
        DOWN
    };
    
    vector<int> spiralOrder(vector<vector<int>>& matrix)
    {
        vector<int> result;
        if (matrix.empty() || matrix.at(0).empty()) return result;
        
        int left = -1;
        int right = matrix.at(0).size();
        int top = -1;
        int bottom = matrix.size();
        
        // hope total size do not overflow
        int totalSize = right * bottom;
        
        int curRow = 0;
        int curCol = 0;
        Direction dir = RIGHT;
        while (totalSize-- > 0)
        {
            result.push_back(matrix.at(curRow).at(curCol));
            if (dir == RIGHT)
            {
                if (curCol+1 == right)
                {
                    top++;
                    dir = DOWN;
                    curRow++;
                }
                else
                {
                	curCol++;
                }
            }
            else if (dir == DOWN)
            {
                if (curRow+1 == bottom)
                {
                    right--;
                    dir = LEFT;
                    curCol--;
                }
                else
                {
                	curRow++;
                }
            }
            else if (dir == LEFT)
            {
                if (curCol-1 == left)
                {
                    bottom--;
                    dir = UP;
                    curRow--;
                }
                else
                {
                	curCol--;
                }
            }
            else
            {
                if (curRow-1 == top)
                {
                    left++;
                    dir = RIGHT;
                    curCol++;
                }
               	else
               	{
               		curRow--;
               	}
            }
        }
        return result;
    }

Log in to reply
 

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