34:顺时针打印矩阵

顺时针打印矩阵

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。

public class Offer35 {
    public static void main(String[] args) {
        int[][] data = {{1,2,3,4},
                        {1,2,3,4},
                        {1,2,3,4}};
        printMatrixInCircle(data);
    }
    //思路:按圈打印,注意边界即可
    public static void printMatrixInCircle(int[][] data){
        int row = data.length;
        int col = data[0].length;
        int start = 0;
        //判断条件
        while (start * 2 < row && start * 2 < col){
            //向右走
            for (int i = start;i<col-start;i++){
                System.out.println(data[start][i]);
            }

            //向下走
            if(start<row-1-start) {
                for (int i = start + 1; i < row - start; i++) {
                    System.out.println(data[i][col-start-1]);
                }
            }

            //向左走
            if(start<col-1-start&&start<row-1-start) {
                for (int i = col-1-start-1; i >= start ; i--) {
                    System.out.println(data[row-1 - start][i]);
                }
            }
            //向上走
            if(start<row-1-start&&start<col-1-start-1)
            for ( int i = row-1-start-1;i>=start+1;i--){
                System.out.println(data[i][start]);
            }
            start++;
        }
    }
}
©️2020 CSDN 皮肤主题: 书香水墨 设计师:CSDN官方博客 返回首页