天天看點

轉圈列印矩陣(二維數組)

  • 問題描述

    給定一個二維數組,轉圈将其列印出來

  • 解決方案

    首先設計一個隻列印一圈的方法,然後循環控制,代碼如下:

//主方法
    public static void circlePrintMatrix(int[][] arr){
        if(arr == null)
            return;
        int row1 = 0;
        int col1 = 0;
        int row2 = arr.length - 1;
        int col2 = arr[0].length - 1;
        while(row1 <= row2 &&  col1 <= col2 ){
            printOneCircle(arr,row1++,col1++,row2--,col2--);
        }
    }

    //隻列印一圈的方法
    public static void printOneCircle(int[][] arr,int row1,int col1,int row2,int col2){
        //隻有一列
        if(col1 == col2){
            for (int i = row1; i <= row2; i++) {
                System.out.print(arr[i][col1] + " ");
            }
        }
        //隻有一行
        else if (row1 == row2){
            for (int i = col1; i <= col2; i++) {
                System.out.print(arr[row1][i] + " ");
            }
        }
        else{
            for (int i = col1; i <= col2; i++) {
                System.out.print(arr[row1][i] + " ");
            }
            for (int i = row1 + 1; i <= row2; i++) {
                System.out.print(arr[i][col2] + " ");
            }
            for (int i = col2 - 1; i >= col1; i--) {
                System.out.print(arr[row2][i] + " ");
            }
            for (int i = row2 - 1; i > row1; i--) {
                System.out.print(arr[i][col1] + " ");
            }
        }
    }