蜗牛排序

发布时间 2023-08-19 12:45:34作者: 我会变强的

题目:

  

——————————————————————————————————————————————————————————

解答:

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

vector<int> snail(vector<vector<int>>& array) {
    vector<int> ret;
    int size = array.size(); // 获取数组的大小
    int rowBegin = 0, rowEnd = size - 1; // 定义行的起始和结束索引
    int colBegin = 0, colEnd = size - 1; // 定义列的起始和结束索引

    while (rowBegin <= rowEnd && colBegin <= colEnd) {
        // 从左到右遍历上行
        for (int col = colBegin; col <= colEnd; ++col) {
            ret.push_back(array[rowBegin][col]);
        }
        ++rowBegin;

        // 从上到下遍历右列
        for (int row = rowBegin; row <= rowEnd; ++row) {
            ret.push_back(array[row][colEnd]);
        }
        --colEnd;

        // 从右到左遍历下行
        for (int col = colEnd; col >= colBegin; --col) {
            ret.push_back(array[rowEnd][col]);
        }
        --rowEnd;

        // 从下到上遍历左列
        for (int row = rowEnd; row >= rowBegin; --row) {
            ret.push_back(array[row][colBegin]);
        }
        ++colBegin;
    }

    return ret;
}

int main() {
    vector<vector<int>> input = {
        { 1, 2, 3, 4 },
        { 5, 6, 7, 8 },
        { 9, 10, 11, 12 },
        { 13, 14, 15, 16 }
    };

    vector<int> result = snail(input);

    for (int i = 0; i < result.size(); i++) {
        cout << result[i] << " ";
    }
    cout << endl;
    return 0;
}

res:

  

(解答中把输入写死了;实际做题 按照具体题目的输入来处理输入)

(〃>_<;〃)(〃>_<;〃)(〃>_<;〃)