ccf 201412-2 Z 字形掃描(100分)
阿新 • • 發佈:2018-12-09
問題描述
在影象編碼的演算法中,需要將一個給定的方形矩陣進行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的正整數。
共有四個方向,每走一步的轉向有上一步的轉向和當前的位置決定。
提交後得100分的C++程式如下:
#include<iostream>
#include<algorithm>
using namespace std;
int a[505][505];
int main()
{
int n;
cin >> n;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
cin >> a[i][j];
}
}
int nowx = 1, nowy = 1 , dirx = -1, diry = 1;
for (int i = 1; i <= n*n; i++)
{
cout << a[nowx][nowy] << " ";
if (dirx == 0 && diry == 1) //如果前一個方向向右走
{
if (nowx == 1) dirx = 1, diry = -1; //方向改為左下
if (nowx == n) dirx = -1, diry = 1;//方向改為右上
nowx += dirx, nowy += diry;
continue ;
}
else if (dirx == 1 && diry == -1)//如果前一個方向為左下
{
if (nowy == 1) dirx = 1, diry = 0;//方向改為下
if (nowx == n) dirx = 0, diry = 1;//方向改為右
nowx += dirx, nowy += diry;
continue;
}
else if (dirx == 1 && diry == 0) //如果前一個方向為下
{
if (nowy == 1) dirx = -1, diry = 1;//方向改為右上
if (nowy == n) dirx = 1, diry = -1;//方向改為左下
nowx += dirx, nowy += diry;
continue;
}
else if (dirx == -1 && diry == 1)//如果前一個方向為右上
{
if (nowx == 1) dirx = 0, diry = 1;//方向改為右
if (nowy == n) dirx = 1, diry = 0;//方向改為下
nowx += dirx, nowy += diry;
continue;
}
}
cout << endl;
return 0;
}