二十:顺时针打印矩阵

题目

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

实现

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[][] matrix = new int[n][m];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                matrix[i][j] = in.nextInt();
            }
        }
        f(matrix);
    }
    
    public static void f(int[][] m) {
        //用两个点a和b,分别表示左上角的点和右下角的点,来控制转圈的打印顺序
        int ah = 0;
        int al = 0;
        int bh = m.length - 1;
        int bl = m[0].length - 1;
        while (ah <= bh && al <= bl) { //注意这里的条件,第二个条件不能少,比如说五行四列的情况
            printEdge(m, ah++, al++, bh--, bl--);
        }
    }
    
    public static void printEdge(int[][] m , int ah, int al, int bh, int bl) {
        //考虑只有一行的情况
        if (ah == bh) {
            while (al <= bl) {
                System.out.print(m[ah][al++] + " ");    
            }
        } else if (al == bl) { //考虑只有一列的情况下
            while (ah <= bh) {
                System.out.print(m[ah++][al] + " ");
            }
        } else { //正常情况下
            int curC = al;
            int curR = ah;
            //打印上面的行
            while (curC < bl) {
                System.out.print(m[curR][curC++] + " ");
            }
            //打印右面的列
            while (curR < bh) {
                System.out.print(m[curR++][curC] + " ");
            }
            //打印下面的行
            while (curC > al) {
                System.out.print(m[curR][curC--] + " ");
            }
            //打印左边的列
            while (curR > ah) {
                System.out.print(m[curR--][curC] + " ");
            }
        }
    }
    
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值