顺时针打印二维数组《算法很美》

题1:顺时针打印二维数组

  1. 1 2 3 4

  2. 5 6 7 8

  3. 9 10 11 12

  4. 13 14 15 16

  5. 1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10

思路: 先设定好边界,行、列,还有初始值。设定好边界后,用while去遍历打印的动作,先右后下再左再上,这个顺时针的动作,因为你会发现其实顺时针的规律也就这样,只要重复循环这个动作即可得出答案。

具体思路:

  1. 设置好边界初始值
  int leftUpRow = 0;
    int leftUpCol = 0;
    int rightDownRow = matrix.length - 1;  //行
    int rightDownCol = matrix[0].length - 1;   //列
  1. while (leftUpRow <= rightDownRow && leftUpCol <= rightDownCol) //设置边界,且遍历
  2. 后面的步骤其实就是右走、下走、左走、上走,顺时针动作
  3. int r = leftUpRow, c = leftUpCol; 实时更新步骤的初始值
  4. 以c为起点向右边走到边界rightDownCol
while (c <= rightDownCol) {
                System.out.print(matrix[r][c++] + " ");
            }
  1. 遍历到 rightDownCol 后
                {1, 2, 3, 4 , 100},
                {5, 6, 7, 8 , 101},
                {9, 10, 11, 12 ,102},
                {13, 14, 15, 16 ,103}
public class 顺时针打印二维数组 {
    public static void main(String[] args){
        int[][] matrix = {
                {1, 2, 3, 4 , 100},
                {5, 6, 7, 8 , 101},
                {9, 10, 11, 12 ,102},
                {13, 14, 15, 16 ,103}
        };
        print(matrix);
    }

    static void print(int[][] matrix) {

        int leftUpRow = 0;
        int leftUpCol = 0;
        int rightDownRow = matrix.length - 1;  //行
        int rightDownCol = matrix[0].length - 1;   //列
        while (leftUpRow <= rightDownRow && leftUpCol <= rightDownCol) {
            int r = leftUpRow; // 行起步
            int c = leftUpCol;  // 列起步
            //上面一条边
            while (c <= rightDownCol) {
                System.out.print(matrix[r][c++] + " ");
            }
            //恢复
            c = rightDownCol;
            r++;
            //右边的一条边
            while (r <= rightDownRow) {
                System.out.print(matrix[r++][c] + " ");
            }
            //恢复
            r = rightDownRow;
            c--;
            //下面一条边
            while (c >= leftUpCol) {
                System.out.print(matrix[r][c--] + " ");
            }
            //恢复
            c = leftUpCol;
            r--;
            while (r > leftUpRow) {
                System.out.print(matrix[r--][c] + " ");
            }

            leftUpRow++;
            leftUpCol++;
            rightDownRow--;
            rightDownCol--;
        }
    }
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值