十九:“之”字形打印矩阵

题目

用zigzag的方式打印矩阵, 比如如下的矩阵
0 1 2 3
4 5 6 7
8 9 10 11
打印顺序为: 0 1 4 8 5 2 3 6 9 10 7 11

实现

import java.util.*;

public class Main {
    
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int m = in.nextInt();
        int[][] arr = new int[n][m];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                arr[i][j] = in.nextInt();
            }
        }

        f(arr);        
    }
    
    //两个点,a和b,刚开始,a往下走,b往右走,最后a右走,b往下走,到最后位置
    //一个变量控制从下往上打印,还是从上往下打印
    public static void f(int[][] m) {
        int ah = 0;
        int al = 0;
        int bh = 0;
        int bl = 0;
        boolean downUp = true;
        int row = m.length;
        int col = m[0].length;
        while (al != col && bh != row) {
            printEdge(m, ah, al, bh, bl, downUp);
            al = ah == row - 1 ? al + 1 : al;
            ah = ah == row - 1 ? ah : ah + 1;
            bh = bl == col - 1 ? bh + 1 : bh;
            bl = bl == col - 1 ? bl : bl + 1;
            downUp = !downUp;
        }
    }
    
    public static void printEdge(int[][] m, int ah, int al, int bh, int bl, boolean downUp) {
        //从下往上打印,对于a点来说,a点的行数ah在不断你的变化
        if (downUp) {
            while (ah != bh - 1) {
                System.out.print(m[ah--][al++] + " ");
            }
        } else { //从上往下打印,对于b点来说,b的行在不断的增加,列在不断的减小
            while (bh != ah + 1) {
                System.out.print(m[bh++][bl--] + " ");
            }
            
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值