问题描述
试题编号: | 201412-2 |
试题名称: | Z字形扫描 |
时间限制: | 2.0s |
内存限制: | 256.0MB |
问题描述: | 问题描述 在图像编码的算法中,需要将一个给定的方形矩阵进行Z字形扫描(Zigzag Scan)。给定一个n×n的矩阵,Z字形扫描的过程如下图所示: 输入格式 输入的第一行包含一个整数n,表示矩阵的大小。 输出格式 输出一行,包含n×n个整数,由空格分隔,表示输入的矩阵经过Z字形扫描后的结果。 样例输入 4 样例输出 1 5 3 9 7 3 9 5 4 7 3 6 6 4 1 3 评测用例规模与约定 1≤n≤500,矩阵元素为不超过1000的正整数。 |
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<iomanip>
using namespace std;
/*
struct Node{
int drow;
int dcol;
};
Node direct[] = {{1, 0}, {0, 1}, {1, -1}, {-1, 1}};
*/
int main()
{
int n, cnt = 0;
cin >> n;
int a[n+2][n+2];
for(int i=0; i<n+2; i++)
for(int j=0; j<n+2; j++)
{
a[i][j] = -1;
}
for(int i=1; i<=n; i++)
{
for(int j=1; j<=n; j++)
{
cin >> a[i][j];
}
}
{ cout << a[1][1] << " ";
cnt++;}
int t = n*n;
int i = 1, j = 1;
while(1)
{
//向右走
if(a[i][j+1]!=-1)
{ cout << a[i][++j] << " ";
cnt++;
a[i][j] = -1;
}
//左下角
while(a[i+1][j-1]!=-1)
{ cout << a[++i][--j] << " ";a[i][j]=-1;cnt++;}
//向下走
// t--;
if(a[i+1][j]!=-1)
{ cout << a[++i][j] << " ";cnt++;a[i][j]=-1;}
//右上角
while(a[i-1][j+1]!=-1)
{ cout << a[--i][++j] << " ";cnt++;a[i][j]=-1;}
if(t == cnt)
break;
}
return 0;
}