试题编号: 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的正整数。
题解:
这题我自己是没想出来的,参考了这个博客的第二种方法,我的代码的思路:
- 先从上三角开始打印,也就是从(1,1)处开始,然后把i分为奇数和偶数做不同的输出。
- 然后再从下三角开始打印,也就是最终到(n,n)处结束,也是把i分为奇数和偶数做不同的输出。
具体的看代码把,n为奇数or为偶数,上三角最终停的位置是不同的(n为偶数停在右上角、n为奇数停在左下角)
通过这道题我发现了一个很玄学的问题:
当我对c++进入读入优化的时候,也就是加入下面的代码,循环中的输出cout << g[x--][y++] << " ";
输出不了结果,只能用printf("%d ",g[x--][y++]);
来替代,删除下面的代码就可以用cout输出了。
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
代码:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <cstring>
#include <string>
#include <algorithm>
#include <vector>
#include <deque>
#include <list>
#include <utility>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <bitset>
#include <iterator>
using namespace std;
typedef long long ll;
const int inf = 0x3f3f3f3f;
const ll INF = 0x3f3f3f3f3f3f3f3f;
const double PI = acos(-1.0);
const double E = exp(1.0);
const int MOD = 1e9+7;
const int MAX = 5e2+5;
int n;
int g[MAX][MAX];
void Scan()
{
// 向下走:行++,x++
// 向右走:列++,y++
// 起点位置(1,1)
int x = 1;
int y = 1;
for(int i = 1; i <= n-1; i++)// 上三角
{
//printf("(%d,%d) i=%d\n",x,y,i);
if(i & 1)
{
// i为奇数
for(int j = 1; j < i; j++)
{
//cout << g[x--][y++] << " ";
printf("%d ",g[x--][y++]);
}
//cout << g[x][y++] << " ";
printf("%d ",g[x][y++]);
}
else
{
// i为偶数
for(int j = 1; j < i; j++)
{
//cout << g[x++][y--] << " ";
printf("%d ",g[x++][y--]);
}
//cout << g[x++][y] << " ";
printf("%d ",g[x++][y]);
}
}
// 如果n为偶数,此时(x,y)位于右上角
// 如果n为奇数,此时(x,y)位于左下角
for(int i = n; i >= 1; i--)// 下三角
{
//printf("(%d,%d) i=%d\n",x,y,i);
if(i & 1)
{
// i为奇数
for(int j = 1; j < i; j++)
{
//cout << g[x--][y++] << " ";
printf("%d ",g[x--][y++]);
}
//cout << g[x++][y] << " ";
printf("%d ",g[x++][y]);
}
else
{
// i为偶数
for(int j = 1; j < i; j++)
{
//cout << g[x++][y--] << " ";
printf("%d ",g[x++][y--]);
}
//cout << g[x][y++] << " ";
printf("%d ",g[x][y++]);
}
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
while(cin >> n)
{
for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= n; j++)
{
cin >> g[i][j];
}
}
// 扫描函数
Scan();
}
return 0;
}