0
点赞
收藏
分享

微信扫一扫

顺时针打印二维数组

伽马星系 2022-03-13 阅读 50

/**

  • 顺时针打印二维数组
    输入
    1,2,3,4
    5,6,7,8
    9,10,11,12
    13,14,15,16
    101,102,103,104
    输出
    1 2 3 4 8 12 16 104 103 102 101 13 9 5 6 7 11 15 14 10
    */
public class test9 {
    public static void main(String[] args) {
        int[][]a={
                {1,2,3,4},
                {5,6,7,8},
                {9,10,11,12},
                {13,14,15,16},
                {101,102,103,104}
        };
     int leftUpRow=0,leftUpCol=0;                         //确定左上角边界
     int rightDownRow =a.length-1,rightDownCol=a[0].length-1;    //右下角边界
     int r=leftUpRow;
     int c=leftUpCol;
  
     while (leftUpRow<= rightDownRow && leftUpCol <=rightDownCol) {     //控制输出的圈数
         r=leftUpRow;
         c=leftUpCol;
         while (c <= rightDownCol) {               //输出上行元素
             System.out.print(a[r][c++] + " ");
         }                       //循环结束时,列越界了
         c--;                   //列恢复到数组范围中
         r++;                    //准备输出右列了
         while (r <= rightDownRow) {            //输出右列
             System.out.print(a[r++][c] + " ");
         }
         r--;        //行恢复到矩阵里,循环结束时,行越界了
         c--;
         while (c >= leftUpCol) {
             System.out.print(a[r][c--] + " ");
         }
         c++;        //列复位
         r--;
         while (r > leftUpRow) {
             System.out.print(a[r--][c] + " ");
         }
         leftUpRow++;         //以下四步骤,为输出第二圈做准备,缩小数组范围
         leftUpCol++;
         rightDownRow--;
         rightDownCol--;

     }
    }
}

举报

相关推荐

0 条评论