题目:
——————————————————————————————————————————————————————————
解答:
#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:
(解答中把输入写死了;实际做题 按照具体题目的输入来处理输入)
(〃>_<;〃)(〃>_<;〃)(〃>_<;〃)
标签:size,int,ret,vector,array,排序,蜗牛,row From: https://www.cnblogs.com/wjjgame/p/17642340.html