劍指offer-05-順時針打印數組

題目描述:輸入一個矩陣,按照從外向裏以順時針的順序依次打印出每一個數字,例如,如果輸入如下矩陣: 1 2 3 4 5 6 7 8 9 10 11 1213 14 15 16 則依次打印出數字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.

package swordRefersToOffer;
import java.util.Scanner;
public class PrintMatrix {
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();   
        int [][] arr = new int[n][n];
        //給數組賦值
        for(int i = 0;i<n;i++){
            for(int j = 0;j<n;j++){
                arr[i][j]=sc.nextInt();
            }
        }
        //將數組的值輸出
        for(int i = 0;i<n;i++){
            for(int j = 0;j<n;j++){
                System.out.print(arr[i][j]+"\t");
                if(j == n-1){
                    System.out.println();
                }
            }
        }
        System.out.println("順時針打印請輸入數組的值");
        printMatr(arr);
    }
    public static void printMatr(int[][] arr){
        int tr = 0;
        int tc = 0;
        int dr = arr.length-1;
        int dc = arr[0].length-1;
        while (tr <= dr && tc <= dc){
             printEdge(arr,tr++,tc++,dr--,dc--);
        }
    }
    
    public static void printEdge(int[][] arr,int tr, int tc, int dr, int dc){
        if(tr == dr){//只有一行
            for(int i =tc;i<dc;i++){
                System.out.print(arr[tr][i]+" ");
            }
        }else if(tc==dc){//只有一列
            for(int i =tr;i<dr;i++){
                System.out.print(arr[i][tr]+" ");
            }
        }else{
            int c = tc;
            int r = tr;
            while(c != dc){
                System.out.print(arr[tr][c]+" ");
                c++;
            }
            
            while(r != dr){
                System.out.print(arr[r][dc]+" ");
                r++;
            }        
            while(c != tc){
                System.out.print(arr[dr][c]+" ");
                c--;
            }          
            while(r != tr){
                System.out.print(arr[r][tc]+" ");
                r--;
            }                      
        }     
    }
}

思想:用左上和右下的座標定位出一次要旋轉打印的數據,一次旋轉打印結束後,往對角分別前進和後退一個單位。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章