AcWing 3208. Z字形扫描
原题链接
简单
作者:
王小强
,
2021-02-16 10:50:51
,
所有人可见
,
阅读 351
算法1:(利用了对角线的性质)
#include <iostream>
#include <vector>
#include <map>
using namespace std;
int n, t;
int main(void) {
scanf("%d", &n);
map<int, vector<int>> m;
for (int y = 0; y < n; ++y)
for (int x = 0; x < n; ++x) {
scanf("%d", &t);
m[x + y].emplace_back(t);
}
for (auto&& [id, vals] : m)
if (id & 1) for (const auto& x : vals) printf("%d ", x);
else for (auto it = vals.rbegin(); it != vals.rend(); ++it) printf("%d ", *it);
return 0;
}
算法2(使用图遍历的方法)
欠债还钱 天津第一
#include <iostream>
#include <vector>
using namespace std;
int n;
void findDiagonalOrder(vector<vector<int>>& matrix) {
int x = 0, y = 0, d = 1, cnt = 0;
while (cnt++ < n * n) {
printf("%d ", matrix[y][x]);
const int nx = x + d, ny = y - d;
if (nx < 0 || ny < 0 || nx == n || ny == n) {
if (d == 1) {
if (nx == n) ++y;
else ++x;
} else {
if (ny == n) ++x;
else ++y;
}
d = -d;
continue;
}
x = nx;
y = ny;
}
}
int main(void) {
scanf("%d", &n);
vector<vector<int>> matrix(n, vector<int>(n));
for (int y = 0; y < n; ++y)
for (int x = 0; x < n; ++x) cin >> matrix[y][x];
findDiagonalOrder(matrix);
}