问题描述
在图像编码的算法中,需要将一个给定的方形矩阵进行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字形扫描的结果。
对于下面的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+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
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<iostream>
#include<stdio.h>
using namespace std;
int main()
{
int numcin[501][501];
int count;
int temp;
int x=1;
int y=1;
bool flag=false;
scanf("%d",&count);
for(int i=1;i<=count;i++)
{
for(int j=1;j<=count;j++)
{
scanf("%d",&numcin[i][j]);
}
}
for(int i=1;i<=count;i++)
{
temp=i;
do{
printf("%d ",numcin[x][y]);
if(flag)
{
++x; //左下移动
y=i+1-x;
}
else
{ //右上移动
--x;
y=i+1-x;
}
}while(--temp);
if(y==0)
{
y=1; //到了上边界
}
if(x==0)
{
x=1; //到了下边界
}
if(flag)
{
flag=false;
}
else{
flag=true;
}
}
if(y==1)
{
y=2;
--x;
}
else
{
x=2;
--y;
}
for(int i=count-1;i>=1;i--)
{
temp=i;
do{
printf("%d ",numcin[x][y]);
if(flag)
{
++x;
y=2*count+1-i-x;
}
else
{
--x;
y=2*count+1-i-x;
}
}while(--temp);
if(x>count)
{
--x;
y=y+2;
}
if(y>count)
{
x=x+2;
--y;
}
if(flag)
{
flag=false;
}
else{
flag=true;
}
}
return 0;
}
好棒的答案(关键在于找规律,左下如果越界一定往下移动,右上如果越界一定往右移动)
#include <iostream>
using namespace std;
int n;
int a[505][505];
bool isBad(int h,int l) { //位置越界判断
return (h<0 || l<0 || h>=n ||l>=n);
}
bool PutMove(int prvs, int h, int l) { //prvs代表经过什么移动到达第h行、第l列的位置
if (prvs == -1){ //除第一个数以外,其他数加空格输出
cout << a[h][l];
if (!isBad(h,l+1)) //其右没越界
PutMove(1,h,l+1); //向右移动
}
else
cout << " " << a[h][l];
if (h == n-1 && l == n-1) //递归结束
return true;
switch(prvs) {
case 0: //↓
if (!isBad(h-1,l+1)) //其右上没越界
PutMove(3,h-1,l+1); //向右上移动
else
PutMove(2,h+1,l-1); //向左下移动
break;
case 1: //→
if (!isBad(h+1,l-1)) //其左下没越界
PutMove(2,h+1,l-1); //向左下移动
else
PutMove(3,h-1,l+1); //向右上移动
break;
case 2: //↙
if (!isBad(h+1,l-1)) //其左下没越界
PutMove(2,h+1,l-1); //向左下移动
else if (!isBad(h+1,l)) //其下没越界
PutMove(0,h+1,l); //向下移动
else
PutMove(1,h,l+1); //向右移动
break;
case 3: //↗
if (!isBad(h-1,l+1)) //其右上没越界
PutMove(3,h-1,l+1); //向右上移动
else if (!isBad(h,l+1)) //其右没越界
PutMove(1,h,l+1); //向右移动
else
PutMove(0,h+1,l); //向下移动
break;
}
}
int main() {
cin >> n;
int i,j;
for (i=0;i<n;i++)
for (j=0;j<n;j++)
cin >> a[i][j];
PutMove(-1,0,0);
return 0;
}