LeetCode-Spiral Matrix

2018-09-20  本文已影响0人  圣地亚哥_SVIP

最主要是边界条件的处理:
1、start_row<=row/2 && start_row<=col/2
2、一行或者一列的情况的处理

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        vector<int> res;
        if(matrix.empty())return res;
        int row = matrix.size()-1;
        int col = matrix[0].size()-1;
        int start_row = 0;
        int row_in = start_row;
        int col_in = start_row;
        for(;start_row<=row/2 && start_row<=col/2;++start_row){
            row_in = start_row;
            col_in = start_row;
            while(col_in <= col - start_row){
                res.push_back(matrix[row_in][col_in]);
                ++col_in;
            }
            col_in=col-start_row;
            row_in++;
            if (row_in > row-start_row)continue;
            while(row_in <= row - start_row){
                res.push_back(matrix[row_in][col_in]);
                ++row_in;
            }
            row_in=row - start_row;
            col_in--;
            if (col_in < start_row)continue;
            while(col_in >= start_row){
                res.push_back(matrix[row_in][col_in]);
                --col_in;
            }
            col_in=start_row;
            row_in--;
            while(row_in > start_row){
                res.push_back(matrix[row_in][col_in]);
                --row_in;
            }
        }
        return res;
    }
};
上一篇下一篇

猜你喜欢

热点阅读