CCF 201412-2 Z字形掃描

來自專欄如何快速高效學習C++?- 計算機軟體能力認證考試系統?

118.190.20.162

試題編號: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 93 7 5 69 4 6 47 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 <vector>#define test 0using namespace std;class solution{ vector<vector<int> >mat; vector<int>res; int res_p=0;public: solution(int n){ mat.resize(n); for(int i=0;i<n;i++){ mat[i].resize(n); } for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ cin>>mat[i][j]; } } res.resize(n*n); } void solve(){ int up=true; int dia=2*(int)mat.size()-2; int lim=(int)mat.size(); for(int i=0;i<=dia;i++){ if(up){ for(int r=i;r>=0;r--){ int c=i-r; if(r<0||r>=lim||c<0||c>=lim)continue; res[res_p++]=mat[r][c]; } }else{ for(int r=0;r<=i;r++){ int c=i-r; if(r<0||r>=lim||c<0||c>=lim)continue; res[res_p++]=mat[r][c]; } } up=!up; } } void print(){ for(int i=0;i<(int)res.size();i++){ cout<<res[i]; if(i!=(int)res.size()-1)cout<< ; } cout<<endl; }};int main(){ int n=0; cin>>n; solution s(n); s.solve(); s.print(); return 0;}

PS:

廣告時間啦~理工狗不想被人文素養拖後腿?不妨關注微信公眾號:

歡迎掃碼關注~


推薦閱讀:
相關文章