回形打印数组

//
//  main.cpp
//  回形打印数组
//
//  Created by lee on 28/09/2018.
//  Copyright © 2018 lee. All rights reserved.
//

#include <iostream>
#include <vector>
using namespace std;

void printEdge(vector<vector<int>> arr, vector<int>& res, int s_x, int s_y, int e_x, int e_y){
    if (s_x == e_x){
        for (int i = s_y; i<= e_y; i++){
            res.push_back(arr[s_x][i]);}
    }
    else if (s_y == e_y){
        for (int i = s_x; i<= e_x; i++){
            res.push_back(arr[i][s_y]);}
    }
    else{
        int curx = s_x;
        int cury = s_y;
        while (cury != e_y){
            res.push_back(arr[s_x][cury++]);
        }

        while (curx != e_x){
            res.push_back(arr[curx++][cury]);
        }

        while (cury != s_y){
            res.push_back(arr[curx][cury--]);
        }

        while (curx != s_x){
            res.push_back(arr[curx--][cury]);
        }
    }
}

vector<int> spiralOrder(vector<vector<int>>& matrix) {
    int s_x = 0;
    int s_y = 0;
    vector<int> res;
    if (matrix.empty()) return res;
    int e_x = (int) matrix.size()-1; // 行
    int e_y = (int) matrix[0].size()-1; //列
    while(s_x <= e_x && s_y <= e_y){
        printEdge(matrix, res, s_x++, s_y++, e_x--, e_y--);
    }
    return res;
}

int main(int argc, const char * argv[]) {
    vector<vector<int>> arr1 = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 },{13,14,15,16}};
    vector<vector<int>> arr2 = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }};
    vector<int> res1;
    vector<int> res2;
    res1 = spiralOrder(arr1);
    for (auto i : res1) cout << i << " ";
    cout << endl;
    res2 = spiralOrder(arr2);
    for (auto i : res2) cout << i << " ";
    cout << endl;
    return 0;
}