leetcode 54:螺旋矩阵

std::vector<int> spiralOrder(std::vector<std::vector<int>>& matrix) {
    std::vector<int> c;
    if(matrix.size()==0)
        return c;
    int top=0;
    int right=matrix[0].size()-1;
    int left=0;
    int bottom=matrix.size()-1;
    int i=0;
    while(top<=bottom&&left<=right){
        if(i%4==0){
            for(int i=left;i<=right;i++) {
                c.push_back(matrix[top][i]);
            }
            top++;
        }
        else if(i%4==1){
            for(int i=top;i<=bottom;i++){
                c.push_back(matrix[i][right]);
            }
            right--;
        }
        else if(i%4==2){
            for(int i=right;i>=left;i--){
                c.push_back(matrix[bottom][i]);
            }
            bottom--;
        }
        else if(i%4==3){
            for(int i=bottom;i>=top;i--){
                c.push_back(matrix[i][left]);
            }
            left++;
        }
        i++;
    }
    return c;
}

猜你喜欢

转载自blog.csdn.net/u013263891/article/details/84454025