问题描述 在图像编码的算法中,需要将一个给定的方形矩阵进行Z字形扫描(Zigzag Scan)。给定一个n×n的矩阵,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
请实现一个Z字形扫描的程序,给定一个n×n的矩阵,输出对这个矩阵进行Z字形扫描的结果。输入格式 输入的第一行包含一个整数n,表示矩阵的大小。
输入的第二行到第n+1行每行包含n个正整数,由空格分隔,表示给定的矩阵。输出格式 输出一行,包含n×n个整数,由空格分隔,表示输入的矩阵经过Z字形扫描后的结果。样例输入4
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评测用例规模与约定 1≤n≤500,矩阵元素为不超过1000的正整数。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 510;
int a[N][N];
int dx[4] = {0, 1, 1, -1}; //右, 左下, 下, 右上
int dy[4] = {1, -1, 0, 1};
int n;
bool check(int x, int y){
if (x < 1 || x > n || y < 1 || y > n) return false;
return true;
}
int main(){
scanf("%d", &n);
for (int i = 1; i <= n; i ++)
for (int j = 1; j <= n; j ++)
scanf("%d", &a[i][j]);
//先向右走(0),然后向左下角走(1),然后向下走(2),然后向上(3)
cout << a[1][1] << " ";
int next = 3;
int x = 1, y = 1;
while(x != n || y != n){
if (next == 3){
if (check(x + dx[3], y + dy[3])){
x = x + dx[3], y = y + dy[3];
next = 3;
if (!check(x, y)) continue;
cout << a[x][y] << " ";
}
else{
x = x + dx[0], y = y + dy[0];
next = 0;
if (!check(x, y)) continue;
cout << a[x][y] << " ";
}
}
else if (next == 1){
if (check(x + dx[1], y + dy[1])){
x = x + dx[1], y = y + dy[1];
next = 1;
if (!check(x, y)) continue;
cout << a[x][y] << " ";
}
else {
x = x + dx[2], y = y + dy[2];
next = 2;
if (!check(x, y)) continue;
cout << a[x][y] << " ";
}
}
else if (next == 0){
x = x + dx[1], y = y + dy[1];
next = 1;
if (!check(x, y)) continue;
cout << a[x][y] << " ";
}
else if (next == 2){
x = x + dx[3], y = y + dy[3];
next = 3;
if (!check(x, y)) continue;
cout << a[x][y] << " ";
}
}
cout << endl;
return 0;
}