ccf z型扫描

  在图像编码的算法中,需要将一个给定的方形矩阵进行Z字形扫描(Zigzag Scan)。给定一个n×n的矩阵,Z字形扫描的过程如下图所示:

《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

  请实现一个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<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;
}
  

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