【CCF】Z字形扫描

问题描述
  在图像编码的算法中,需要将一个给定的方形矩阵进行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 #include <iostream>
 2 #include <iomanip>
 3 #include <cstdio>
 4 #include <string.h>
 5 #include <cstring>
 6 #include <algorithm>
 7 #include <cmath>
 8 #include <string>
 9 #include <queue>
10 #include <map>
11 #include <vector>
12 #include <set>
13 #include <list>
14 using namespace std;
15 typedef long long ll;
16 const int INF = 0x3f3f3f3f;
17 const int NINF = 0xc0c0c0c0;
18 const int maxn = 505;
19 int MonthDay[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
20 string MonthName[] = {"Jan","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};
21 string DayName[] = {"Sun", "Mon","Tue","Wed","Thu","Fri","Sat"};
22 int s[maxn][maxn];
23 
24 int main() {

27     int n;
28     cin >> n;
29     for(int i = 0; i < n; i++) {
30         for(int j = 0; j < n; j++){
31             cin >> s[i][j];
32         }
33     }
34     int r = 0, c = 0;
35     int choice = 1;
36     while(r != n-1 || c != n-1) {
37         cout << s[r][c] << " ";
38         if(choice == 1) {//right
39             c++;
40             if(r == 0) choice = 4;//leftdown
41             else choice = 2; //rightup
42         }
43         else if(choice == 2) {//rightup
44             r--;
45             c++;
46             if(r == 0 && c != n-1) choice = 1;//down
47             else if(c == n-1) choice = 3;//down
48 
49         }
50         else if(choice == 3) {//down
51             r++;
52             if(c == 0) choice = 2;//rightup
53             else choice = 4;//leftdown
54         }
55         else if(choice == 4) {//leftdown
56             r++;
57             c--;
58             if(r != n-1 && c == 0) choice = 3;//down
59             else if(r == n-1) choice = 1; //right
60         }
61     }
62     cout << s[n-1][n-1] << endl;
63     return 0;
64 }

 

posted @ 2018-03-10 18:58  kikii233  阅读(449)  评论(0编辑  收藏  举报