Straightforward C++ solution


  • 0
    G
        vector<int> spiralOrder(vector<vector<int>>& matrix) {
            vector<int> r;
            if (matrix.empty()) return r;
            int top = 0, bottom = matrix.size() - 1, left = 0, right = matrix[0].size() - 1;
            while (left <= right && top <= bottom) {
                for (int j = left; j <= right && top <= bottom; j++) {
                    r.push_back(matrix[top][j]);
                }
                top++;
    
                for (int i = top; i <= bottom && left <= right; i++) {
                    r.push_back(matrix[i][right]);
                }
                right--;
    
                for (int j = right; j >= left && top <= bottom; j--) {
                    r.push_back(matrix[bottom][j]);
                }
                bottom--;
    
                for (int i = bottom; i >= top && left <= right; i--) {
                    r.push_back(matrix[i][left]);
                }
                left++;
            }
            return r;
        }
    

Log in to reply
 

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