蛇形打印矩阵

用双指针的方法蛇形打印矩阵

示意图:

蛇形矩阵含义
所以蛇形打印的顺序可以看作两个指针的同时移动,每次需要打印的内容就是两个只针对角线上所对应的内容,每移动一次打印的方向就改变一次,直到任意一个起点移动到最后一个顶点的位置。

package chap1;

/**
 * @author your_tt
 * @date 2021年05月25日16:19
 */
public class Serpentine_matrix {
    public static void serpentine(int[][] matrix) {
    //a代表先向右移动的指针,b代表先向下移动的指针
        int ax = 0;
        int ay = 0;
        int bx = 0;
        int by = 0;
        int endx = matrix.length - 1;
        int endy = matrix[0].length - 1;

        boolean fromUp = false;
        while (ax <= endx) {
            printLevel(matrix, ax, ay, bx, by, fromUp);
            ax = ay == endy ? ax + 1 : ax;
            ay = ay == endy ? ay : ay + 1;
            //这里必须注意移动坐标变换的顺序,b向下移动,在没有到达endx前改变的是纵坐标,所以应当是先对by进行坐标判断,否则会出现下标越界的情况!
            by = bx == endx ? by + 1 : by;
            bx = bx == endx ? bx : bx + 1;
            fromUp = !fromUp;
        }
    }

    public static void printLevel(int[][] m, int ax, int ay, int bx, int by, boolean f) {
        if (f) {//上到下
            while (ay >= by) {
                System.out.print(m[ax++][ay--] + " ");
            }
        } else {//下到上
            while (ax <= bx) {
                System.out.print(m[bx--][by++] + " ");
            }
        }
    }
    public static void main(String[] args) {
    //测试数据
        int[][] matrix = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
        serpentine(matrix);
    }
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值