參考博客: http://yangyingming.com/article/371/java
1 //輸入一個正整數n(n<=30),輸出n所對應的蛇形矩陣。舉兩個例子: 2 //n=10時,蛇形矩陣爲: 3 //具體的蛇形矩陣變化路徑見下圖: 4 // 5 // 6 // 7 8 import java.util.Scanner; 9 public class testSheXin { 10 11 /** 12 * @param args 13 */ 14 public static Scanner Sc = new Scanner(System.in); 15 public static void main(String[] args) { 16 // TODO Auto-generated method stub 17 18 System.out.println("輸入一個不大於30的正整數"); 19 int num=0; 20 try{ 21 num = Sc.nextInt(); 22 }catch(Exception e){ 23 e.printStackTrace(); 24 } 25 Print(num); 26 27 28 29 } 30 31 private static int [][] CreatAry(int num ){ 32 int temp = num , rowid = 0 , colid = 0 ; 33 int xcot = 1 ;//斜角長度 34 int count =0;//當前斜角已有長度; 35 int bol = 1;// 1 表示當前應該橫走,-1表示應該豎着走 36 37 int [][] ina = new int [10][10]; 38 while(temp>0){ 39 40 ina[rowid][colid]=temp; 41 count++; 42 if(count >= xcot){//該換行了(斜行) 43 xcot++; 44 count=0; 45 if(bol==1){ 46 colid++; 47 bol=-bol; 48 }else{ 49 rowid++; 50 bol=-bol; 51 } 52 }else{ //不須要換行(斜行) 53 //上次換行後 bol 已經取反,故bol=-1表示此時向斜下走,bol=1 同理; 54 if(bol==-1){ 55 rowid++; 56 colid--; 57 }else{ 58 rowid--; 59 colid++; 60 } 61 62 } 63 64 temp--; 65 66 } 67 return ina; 68 } 69 public static void Print (int num){ 70 int [][] ia= CreatAry(num); 71 for(int i =0;i <ia.length;i++ ){ 72 for(int j =0 ; j<ia.length; j++){ 73 if(ia[i][j]!=0){ 74 System.out.print(ia[i][j]+" "); 75 } 76 } 77 System.out.println(); 78 } 79 } 80 }