对于下面的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+1行每行包含n个正整数,由空格分隔,表示给定的矩阵。
1 5 3 9
3 7 5 6
9 4 6 4
7 3 1 3
附上代码:
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<stack>
using namespace std;
#define size 500
int map[size+5][size+5];
int main()
{
int n;
int i,j;
cin>>n;
for(i=1;i<=n;i++){
for(j=1;j<=n;j++){
cin>>map[i][j];
}
}
int nn=2*n;
int a=1,b=2;
cout<<map[1][1];
if(n==1)
return 0;
while(a+b<=n){
if(a==1){
cout<<" "<<map[a][b];
while(b>1){
cout<<" "<<map[++a][--b];
}
a++;
}
else{
if(b==1){
cout<<" "<<map[a][b];
while(a>1){
cout<<" "<<map[--a][++b];
}
b++;
}
}
}
if(a==n){
cout<<" "<<map[a][b];
while(b<n){
cout<<" "<<map[--a][++b];
}
a++;
}
else{
cout<<" "<<map[a][b];
while(a<n){
cout<<" "<<map[++a][--b];
}
b++;
}
while(a+b<=nn){
if(a==n){
cout<<" "<<map[a][b];
while(b<n){
cout<<" "<<map[--a][++b];
}
a++;
}
else{
if(b==n){
cout<<" "<<map[a][b];
while(a<n){
cout<<" "<<map[++a][--b];
}
b++;
}
}
}
cout<<endl;
return 0;
}