[Leetcode] Spiral Matrix

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int> > &mat) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<int> res;
        
        int r = mat.size();
        if (r == 0) return res;
        
        int c = mat[0].size();
        if (c == 0) return res;
        
        int bri = 0;
        int bci = 0;
        
        while (r > 0 && c > 0)
        {
            if (r == 1)
            {
                for (int i = bci; i < bci + c; ++i)
                    res.push_back(mat[bci][i]);
                break;
            }
            else if (c == 1)
            {
                for (int i = bri; i < bri + r; ++i)
                    res.push_back(mat[i][bri]);
                break;
            }
            
            // top
            for (int i = bci; i < bci + c; ++i)
                res.push_back(mat[bri][i]);
            // right
            for (int i = bri + 1; i < bri + r; ++i)
                res.push_back(mat[i][bci + c - 1]);
                
            for (int i = bci + c - 2; i >= bci; --i)
                res.push_back(mat[bri + r - 1][i]);
                
            for (int i = bri + r - 2; i > bri; --i)
                res.push_back(mat[i][bci]);
                
            r -= 2;
            c -= 2;
            bri++;
            bci++;
        }
        return res;
    }
};

你可能感兴趣的:([Leetcode] Spiral Matrix)