CCF 201412-2 Z字形扫描

来源:互联网 发布:1hhhh域名升级访问中 编辑:程序博客网 时间:2024/05/29 17:32

试题编号: 201412-2
试题名称: Z字形扫描
时间限制: 2.0s
内存限制: 256.0MB
问题描述:
  在图像编码的算法中,需要将一个给定的方形矩阵进行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<bits\stdc++.h>using namespace std;const int N = 501;struct {    int drow;    int dcol;} dir[] = { { 0, 1 },{ 1, 0 },{ 1, -1 },{ -1, 1 } };  //右,下,左下,右上const int RIGHT = 0;const int DOWN = 1;const int LEFT_DOWN = 2;const int RIGHT_UP = 3;int main() {    int n, mat[N][N];    cin >> n;    for (int i = 0; i < n; i++) {        for (int j = 0; j < n; j++) {            cin >> mat[i][j];        }    }    int cur_row = 0, cur_col = 0, next = RIGHT;    cout << mat[cur_row][cur_col];    while (cur_row != n - 1 || cur_col != n - 1) {        cur_row += dir[next].drow;        cur_col += dir[next].dcol;        cout << " " << mat[cur_row][cur_col];        //第一次拐点        if (next == RIGHT &&cur_row == 0) {            next = LEFT_DOWN;        }        else if (next == RIGHT&&cur_row == n - 1) {            next = RIGHT_UP;        }        else if (next == DOWN && cur_col == 0) {            next = RIGHT_UP;        }        else if (next == DOWN && cur_col == n - 1) {            next = LEFT_DOWN;        }        else if (next == LEFT_DOWN && cur_row == n - 1) {            next = RIGHT;        }        else if (next == LEFT_DOWN && cur_col == 0) {            next = DOWN;        }        else if (next == RIGHT_UP && cur_col == n - 1) {            next = DOWN;        }        else if (next == RIGHT_UP && cur_row == 0) {            next = RIGHT;        }    }    return 0;}
原创粉丝点击