Spiral Matrix


Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

https://leetcode.com/problems/spiral-matrix/

Solution


class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        vector<int> ret;
        if(matrix.empty()) return ret;
        int sx=0, ex=matrix[0].size()-1;
        int sy = 0, ey = matrix.size()-1;
        while(true) {
            if(sx > ex) break;
            for(int i=sx; i<=ex; i++) {
                ret.push_back(matrix[sy][i]);
            }
            sy++;
            if(sy > ey) break;
            for(int i=sy; i<=ey; i++) {
                ret.push_back(matrix[i][ex]);
            }
            ex--;
            if(ex < sx) break;
            for(int i=ex; i>=sx; i--) {
                ret.push_back(matrix[ey][i]);
            }
            ey--;
            if(ey < sy) break;
            for(int i=ey; i>=sy; i--) {
                ret.push_back(matrix[i][sx]);
            }
            sx++;
        }
        return ret;
    }
};

results matching ""

    No results matching ""