美文网首页
LeetCode-Spiral Matrix

LeetCode-Spiral Matrix

作者: 圣地亚哥_SVIP | 来源:发表于2018-09-20 09:31 被阅读0次

    最主要是边界条件的处理:
    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;
        }
    };
    

    相关文章

      网友评论

          本文标题:LeetCode-Spiral Matrix

          本文链接:https://www.haomeiwen.com/subject/aldgnftx.html