1. 程式人生 > >輸入一個矩陣 將這個矩陣順時針以順時針的順序依次列印 java實現

輸入一個矩陣 將這個矩陣順時針以順時針的順序依次列印 java實現

/**

  • 輸入一個矩陣 將這個矩陣順時針以順時針的順序依次列印

  • 1 2 3

  • 4 5 6 ——>1 2 3 6 9 8 7 4 5

  • 7 8 9

  • @author Administrator
    *解題的思路就是從最外層開始輸出,然後一圈一圈的向內收縮輸出
    */
    public class JuZhen {
    public static void main(String[] args) {
    //測試資料
    int [][]nums={{1,2,3},{4,5,6},{7,8,9}};
    int [][]nums2={{1,2,3,4},{5,6,7,8},{9,10,11,12}};
    int [][]nums3={{1,2},{3,4}};
    int [][]nums4={{1}};
    int [][]nums5={{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
    int [][]nums6={{1,2,3,4,5},{6,7,8,9,10},{11,12,13,14,15}};
    shuChu(0,0,nums6.length-1,nums6[0].length-1,nums6);
    }

    public static void shuChu(int starX,int starY,int endX,int endY,int [][]nums){

     //解決類似 7 8 9 這樣的數 如果不寫這個陣列就會輸出 7 8 9 8 7
     if(starX==endX){
     	//輸出一層
     	for (int i = starY; i < endY+1; i++) {
     		System.out.print(nums[starX][i]+" ");
     	}
     	return;
     }
     if(starY==endY){
     	for (int i = starX+1; i < endX+1; i++) {
     		System.out.print(nums[i][endY]+" ");
     	}
     }
     
     //輸出一層
     for (int i = starY; i < endY+1; i++) {
     	System.out.print(nums[starX][i]+" ");
     }	
     for (int i = starX+1; i < endX+1; i++) {
     	System.out.print(nums[i][endY]+" ");
     }
     for (int i = endY-1; i >=starY; i--) {
     	System.out.print(nums[endX][i]+" ");
     }
     for (int i = endX-1; i >starX; i--) {
     	System.out.print(nums[i][starY]+" ");
     }
     
     //判斷此時這一個環的形態
     if(starX+1>endX-1||starY+1>endY-1){
     	//最後一個矩陣是矩形 高大於2
     	return;
     }
     if(starX==endX&&starY==endY){
     	//最後一個矩陣是的單個
     	return;
     }
     if(starX+1==endX&&starY+1==endY){
     	//最後一個矩陣是田字格
     	return;
     }
     shuChu(starX+1, starY+1, endX-1, endY-1, nums);
    

    }

}