Succinct C++ solution with explanation.


  • 0
    W
    class Solution {
    public:
        vector<int> spiralOrder(vector<vector<int>>& matrix) {
            vector<int> result;
            // When the matrix is empty;
            if (matrix.empty() || matrix[0].empty()) {
                return result;
            }
            
            int rowSize = matrix.size();
            int colSize = matrix[0].size();
            int totalNum  = rowSize*colSize;
            
            // 0--moveright; 1--movedown; 2--moveleft; 3--moveup;
            int state = 3;
            
            int rowIndex = 0;
            int colIndex = 0;
            while (totalNum--) {
                // Decide whether the current state should change or not;
                int left = (state == 3 || state == 0) ? rowIndex : (rowSize-1-rowIndex);
                int right = (state == 3 || state == 2) ? colIndex : (colSize-1-colIndex);
                if (left == right) {
                    state = (state + 1) % 4;
                }
                // Deal with the case when there is one column left for next perimeter.
                if (state == 0 && rowIndex == (colSize-1-colIndex)) {
                    state++;
                }
                
                // Store the element from matrix to result;
                result.push_back(matrix[rowIndex][colIndex]);
                
                // Decide the position go next;
                // When reach the end of one perimeter, direction need to turn to next inner perimeter.
                if (state == 3 && (rowIndex-1) == colIndex) {
                    colIndex += 1;
                }
                else {
                    rowIndex += (state == 1) ? 1 : ((state == 3) ? -1 : 0);
                    colIndex += (state == 0) ? 1 : ((state == 2) ? -1 : 0);
                }
            }
            
            return result;
        }
    };

Log in to reply
 

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