1. 程式人生 > >CCF CSP認證 題解:201412-2 Z字形掃描(Java語言原創)

CCF CSP認證 題解:201412-2 Z字形掃描(Java語言原創)

問題描述  在影象編碼的演算法中,需要將一個給定的方形矩陣進行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的正整數。

import

java.util.*;

publicclass Main {

static int a[][],n;

privatestaticvoid p(intx, inty) {

System.out.print(" "+a[x][y]);

}

public static void main(String args[]){

Scanner in=new Scanner(System.in);

n=in.nextInt();

a=new int[n+1][n+1];

for(int i=1;i<=n;i++)

for(int j=1;j<=n;j++){

a[i][j]=in.nextInt();

}

System.out

.print(a[1][1]);

if(n>1){//---------少此判斷扣10分

int x=1,y=1;

while(true){//------------------------左上半遍歷

p(x,++y);// →

while(y>1)p(++x,--y);//↙

if(n%2==0&&x==n&&y==1)break;//---偶 左上半結束

p(++x,y);// ↓

while(x>1)p(--x,++y);// ↗

if(n%2==1&&x==1&&y==n)break;//---奇 左上半結束 

}

if(n%2==1){//---奇 額外增加

p(++x

,y);// ↓

while(x<n)p(++x,--y);//↙

}

while(true){//------------------------右下半遍歷

p(x,++y);// →

if(x==n&&y==n)break;//---右下半結束

while(y<n)p(--x,++y);// ↗

p(++x,y);// ↓

while(x<n)p(++x,--y);//↙

}

}

}

}