輸出蛇形矩陣(java版)
阿新 • • 發佈:2019-02-07
import java.util.Scanner; public class HuixingJZ{ public static void main(String[]args){ Scanner sc=new Scanner(System.in); System.out.println("Please enter n:"); int n=sc.nextInt(); printJZ(n); } public static void printJZ(int n){ int [][]A=new int[n][n]; int t=1; int i=0; int j=0; for(int k=0;k<n/2;k++){//k代表第幾圈 for(i=k,j=k;j<n-k-1;j++){//第一條邊 A[i][j]=t++; } for(i=k,j=n-k-1;i<n-k-1;i++){//第二條邊 A[i][j]=t++; } for(i=n-k-1,j=n-k-1;j>k;j--){//第三條邊 A[i][j]=t++; } for(i=n-k-1,j=k;i>k;i--){//第四條邊 A[i][j]=t++; } } if(n%2==1){ A[n/2][n/2]=t; } for(i=0;i<n;i++){ for (j=0;j<n;j++) { System.out.print(A[i][j]+" "); } System.out.println(); } } }
驗證:
Please enter n:
3
1 2 3
8 9 4
7 6 5
Please enter n:
5
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
Please enter n:
6
1 2 3 4 5 6
20 21 22 23 24 7
19 32 33 34 25 8
18 31 36 35 26 9
17 30 29 28 27 10
16 15 14 13 12 11
驗證成功!!!