# CCF_Z 字形扫描

对于下面的 4×4 的矩阵

1     5    3     9

3    7    5     6

9    4     6     4

7    3    1     3

对其进行 Z 字形扫描后得到长度为 16 的序列：

1 5 3 9 7 3 9 5 4 7 3 6 6 4 1 3

1 5 3 9

3 7 5 6

9 4 6 4

7 3 1 3

1 5 3 9 7 3 9 5 4 7 3 6 6 4 1 3

``````#include <stdio.h>
#include <iostream>
#include <queue>
#include <map>
#include <vector>
#include <cmath>
#include <algorithm>
#include <string.h>
#define RIGHT 1
#define DOWN 3
#define XIE_UP 4
#define XIE_DOWN 2

using namespace std;

int a[505][505];
int n;
bool C(int x, int y) {
if (1 <= x && x <= n && 1 <= y && y <= n)
return true;
else
return false;
}

int main() {
// freopen("in.txt", "r", stdin);

scanf("%d", &n);
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
scanf("%d", &a[i][j]);
}
}
// init
int x = 1;
int y = 1;

int st = RIGHT;
int show = 0;
int is_down = 0;
printf("%d ", a[x][y]);
while(1) {
if (x == n && y == n) {
break;
}
switch (st) {
case RIGHT:
if (C(x, y+1)) {
y = y + 1;
printf("%d ", a[x][y]);
if (is_down == 1)
st = XIE_UP;
else
st = XIE_DOWN;
}
break;
case XIE_DOWN:
if (C(x+1, y-1)) {
x++;
y--;
printf("%d ", a[x][y]);
st = XIE_DOWN;
} else {
st = DOWN;
}
is_down = 1;
break;
case DOWN:
if (C(x+1, y)) {
x++;
printf("%d ", a[x][y]);
if (is_down == 1)
st = XIE_UP;
else
st = XIE_DOWN;
} else {
st = RIGHT;
}
break;
case XIE_UP:

if (C(x-1, y+1)) {
x--;
y++;
printf("%d ", a[x][y]);
st = XIE_UP;
} else if (C(x, y+1)){
y++;
printf("%d ", a[x][y]);
st = XIE_DOWN;
} else {
st = DOWN;
show = 1;
}
is_down = 0;
break;
}
}
}
``````

原文作者：Z字形编排问题
原文地址: https://blog.csdn.net/qq_33096883/article/details/51098959
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。