文章
116
粉丝
133
获赞
206
访问
70.1k
分类:模拟 难度:中等
按「右 → 下 → 左 → 上」四条边一圈一圈地剥。维护四个边界:
top、bottom:还没遍历的行范围;
left、right:还没遍历的列范围。
每一轮依次走:上边(left → right)、右边(top+1 → bottom)、下边(right-1 → left)、左边(bottom-1 → top+1),走完把对应边界往里收一格。当 top > bottom 或 left > right 时结束。
关键在收边时的判断:走完上边和右边后,如果 top > bottom 说明只剩一行(或者已经空了),此时不能再走「下边」,否则会把同一行重复输出;同理,走完下边后如果 left > right,不能再走「左边」。这两处判断是本题唯一的坑点。
例如 1 × 5 的矩阵:走完上边后 top 已经超过 bottom,后面三条边全部跳过,结果就是 1 2 3 4 5。
输入是多组、读到文件末尾,并且行末不能有多余空格——用「除了第一个元素,输出前先打一个空格」的写法最省事。
时间复杂度:O(mn)
空间复杂度:O(1)(不计答案数组)
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int m, n;
while (cin >> m >> n) {
vector<vector<int>> a(m, vector<int>(n));
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++) cin >> a[i][j];
int top = 0, bottom = m - 1, left = 0, right = n - 1;
vector<int> order;
order.reserve(m * ...
登录后发布评论
暂无评论,来抢沙发