ccf 201412-2 Z 字形扫描(100分)

问题描述
  在图像编码的算法中,需要将一个给定的方形矩阵进行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的正整数。
  共有四个方向,每走一步的转向有上一步的转向和当前的位置决定。
  提交后得100分的C++程序如下:
  

#include<iostream>
#include<algorithm>
using namespace std;
int a[505][505];
int main()
{
    int n;
    cin >> n;
    for (int i = 1; i <= n; i++)
    {
        for (int j = 1; j <= n; j++)
        {
            cin >> a[i][j];
        }
    }
    int nowx = 1, nowy = 1, dirx = -1, diry = 1;
    for (int i = 1; i <= n*n; i++)
    {
        cout << a[nowx][nowy] << " ";
        if (dirx == 0 && diry == 1) //如果前一个方向向右走
        {
            if (nowx == 1) dirx = 1, diry = -1; //方向改为左下
            if (nowx == n) dirx = -1, diry = 1;//方向改为右上
            nowx += dirx, nowy += diry;
            continue;
        }
        else if (dirx == 1 && diry == -1)//如果前一个方向为左下
        {
            if (nowy == 1) dirx = 1, diry = 0;//方向改为下
            if (nowx == n) dirx = 0, diry = 1;//方向改为右
            nowx += dirx, nowy += diry;
            continue;
        }
        else if (dirx == 1 && diry == 0) //如果前一个方向为下
        {
            if (nowy == 1) dirx = -1, diry = 1;//方向改为右上
            if (nowy == n) dirx = 1, diry = -1;//方向改为左下
            nowx += dirx, nowy += diry;
            continue;
        }
        else if (dirx == -1 && diry == 1)//如果前一个方向为右上
        {
            if (nowx == 1) dirx = 0, diry = 1;//方向改为右
            if (nowy == n) dirx = 1, diry = 0;//方向改为下
            nowx += dirx, nowy += diry;
            continue;
        }
    }
    cout << endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/jinduo16/article/details/82702770