CCFCSP201412-2Z字形扫描

题目
http://118.190.20.162/view.page?gpid=T20

问题描述
  在图像编码的算法中,需要将一个给定的方形矩阵进行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的正整数。

/*
http://118.190.20.162/view.page?gpid=T20
*/
#include <iostream>
using namespace std;

#define RIGHT 0
#define DOWN 1
#define LEFTDOWN 2
#define RIGHTUP 3

int main()
{
    int n;
    cin>>n;
    int matrix[n][n];
    for(int i = 0; i < n; i++)
    {
        for(int j = 0; j < n; j++)
        {
            cin>>matrix[i][j];
        }
    } 
    int next[4][2];
    next[0][0] = 0;
    next[0][1] = 1;
    next[1][0] = 1;
    next[1][1] = 0;
    next[2][0] = 1;
    next[2][1] = -1;
    next[3][0] = -1;
    next[3][1] = 1;
    int row = 0;
    int col = 0;
    int direct = RIGHT;
    cout<<matrix[row][col];
    while(row != n - 1 || col != n - 1 )
    {
        row += next[direct][0];
        col += next[direct][1];
        cout<<" "<<matrix[row][col];
        if(direct == RIGHT && row == 0)
        {
            direct = LEFTDOWN;
        }
        else if(direct == RIGHT && row == n - 1)
        {
            direct = RIGHTUP;
        } 
        else if(direct == LEFTDOWN && row == n - 1)
        {
            direct = RIGHT;
        }
        else if(direct == LEFTDOWN && col == 0)
        {
            direct = DOWN;
        }
        else if(direct == DOWN && col == 0)
        {
            direct = RIGHTUP;
        }
        else if(direct == DOWN && col == n - 1)
        {
            direct = LEFTDOWN;
        }
        else if(direct == RIGHTUP && col == n-1)
        {
            direct = DOWN;
        }
        else if(direct == RIGHTUP && row == 0)
        {
            direct = RIGHT;
        }

    }
    cout<<endl;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值