天天看點

矩陣,有意思。

public class Test4 {

	/*
	01--02  06--07  15--16  28--29      
	   /   /   /   /   /   /   /
	03  05  08  14  17  27  30  43      
	 | /   /   /   /   /   /   / |
	04  09  13  18  26  31  42  44     
	   /   /   /   /   /   /   /
	10  12  19  25  32  41  45  54      
	 | /   /   /   /   /   /   / |
	11  20  24  33  40  46  53  55    
	   /   /   /   /   /   /   /
	21  23  34  39  47  52  56  61    
	 | /   /   /   /   /   /   / |
	22  35  38  48  51  57  60  62    
	   /   /   /   /   /   /   /
	36--37  49--50  58--59  63--64     
	*/
 
	public static void main(String[] args) {
		Test4 t=new Test4();
		t.printData(t.test2(8));
	}
	
	
	//核心算法
    public int[][] test2(int n){
		int arr[][]=new int[n][n];
		for (int i = 0; i < n; i++) {
			for (int j=0,c=i;j<=i&&c>=0;j++,c--) {
				if(i%2==0){  //偶數行
					 if(c==i){ //建立與上次循環的關系
						 if(c==0)
							arr[c][j]=1;
						 else
					       arr[c][j]=arr[c-1][j]+1;
					 }
					 else 
				        arr[c][j]=arr[c+1][j-1]+1;
				}else{ //奇數行
				     if(c==i)
				        arr[j][c]=arr[j][c-1]+1;  //建立與上次循環的關系
				     else
				       arr[j][c]=arr[j-1][c+1]+1;
				}
			}
	   }
		return arr;
	}

	//列印資料
	public void printData(int arr[][]){
		int n=arr.length;
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < n; j++) {	
				if(arr[i][j]>=10)
				  System.out.print(arr[i][j]+" ");
				else
				  if(arr[i][j]!=0)
				  System.out.print("0"+arr[i][j]+" ");
				
			}
			System.out.println();
		}
	}
	
}	
           

這道題目我感肯定大家會過瘾,希望有高手可以想出更簡單的方法,我的思路就是斜着看,通過斜着的循環列印出該效果“

我的效果如圖:

矩陣,有意思。

繼續閱讀