第三次CCF計算機軟體能力認證考試題解(Java)--201412--Z字形掃描--100分通過
阿新 • • 發佈:2019-01-05
注意事項import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n; n=sc.nextInt(); int[][] matrix=new int[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { matrix[i][j]=sc.nextInt(); } } for (int i = 0; i < n; i++) { int row=0; int column=0; if (i%2==0) { row=i; column=0; System.out.print(matrix[row][column]+" "); while (row-1>=0&&column+1<n) { row--; column++; System.out.print(matrix[row][column]+" "); } } else { row=0; column=i; System.out.print(matrix[row][column]+" "); while (row+1<n&&column-1>=0) { row++; column--; System.out.print(matrix[row][column]+" "); } } } for (int i = 1; i <n ; i++) { int row=0; int column=0; if(n%2!=0){ if (i%2==0) { row=n-1; column=i; System.out.print(matrix[row][column]+" "); while (row-1>=0&&column+1<n) { row--; column++; System.out.print(matrix[row][column]+" "); } } else { row=i; column=n-1; System.out.print(matrix[row][column]+" "); while (row+1<n&&column-1>=0) { row++; column--; System.out.print(matrix[row][column]+" "); } } } else { if (i%2==0) { row=i; column=n-1; System.out.print(matrix[row][column]+" "); while (row+1<n&&column-1>=0) { row++; column--; System.out.print(matrix[row][column]+" "); } } else { row=n-1; column=i; System.out.print(matrix[row][column]+" "); while (row-1>=0&&column+1<n) { row--; column++; System.out.print(matrix[row][column]+" "); } } } } } }
該程式碼已在CCF認證平臺上滿分100分通過,將程式碼複製到CCF認證平臺上進行測試時,注意其提交要求,我的程式沒有使用package語句來定義包的資訊。(如果定義了將無法評測),所以需要將以上程式碼的package語句刪除,注意掃描輸出矩陣對角線的後半部分時矩陣的大小n要分奇數、偶數兩種情況進行討論,n為奇數時,開始掃描方向為左下角,n為偶數時,開始掃描方向為右上角