题目
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;
}