(Java热门面试题)怎么顺时针打印一个二维数组

想要顺时针打印二维数组,其实只需要搞定两个点,一个是左上角的坐标(a,b),一个是右下角的坐标(c,d),比如我开辟了一个4x4的二维数组,里面有

注意:a,b,c,d四个点的自增自减操作都是在对应副本变量上,a,b,c,d本身并没有进行任何操作,b++或c++这样的写法只是为了书写方便,并没有改变其本身的值,了解完原理后看源码就明白了。

在这里插入图片描述
左上角坐标为(0,0),右下角坐标为(3,3),有了这两个坐标就太简单了,只需要让a不变,b++,直到4这个位置停下来,打印1,2,3在这里插入图片描述
然后d不变,c++,直到16停止,打印4,8,12在这里插入图片描述
这时候c不变,d–,直到13为止:
在这里插入图片描述
最后b不变,c–,直到1停止,所有这些操作都是左闭右开区间:
在这里插入图片描述
第一圈执行完毕后,只需要a++,b++,c–,d–,循环终止条件是a>c并且b>d
直接上代码:

package Mianshi;

public class Print_Martrix {
    public static void print(int[][] arr) {
        int a = 0;
        int b = 0;
        int c = arr.length - 1;
        int d = arr[0].length-1;
        while (a <= c && b <= d ) {
           print(arr, a++, b++, c--, d--);//每次循环后左上角和右下角向中间靠拢
        }
    }
    private static void print(int[][] arr, int a, int b, int c, int d) {
        //如果是一行数据
        if(a == c) {
            for (int i = 0; i <= d; i++) {
                System.out.print(arr[a][i]);
            }
        //如果是一列元素
        }else if (b == d) {
            for (int i = 0; i < c; i++) {
                System.out.print(arr[i][b]);
            }
            //如果是长方形矩阵,执行以下代码
        }else {
            int curA = a;//a,b,c,d永远不变,只变a,b的副本
            int curB = b;
            //如果左上角列不等于右下角的列
            while (curB != d){
                System.out.print(arr[a][curB++] + " ");
            }
            //如果左上角的行不等于右下角的行
            while (curA != c) {
                System.out.print(arr[curA++][d] + " ");
            }
            //如果新的左上角的列不等于旧左上角的列
            while (curB != b) {
                System.out.print(arr[c][curB--] + " ");
            }
            //如果新的左上角的行不等于旧左上角的行
            while (curA != a) {
                System.out.print(arr[curA--][b] + " ");
            }
        }
    }
    public static void main(String[] args) {
        int[][] matrix = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 },
                { 13, 14, 15, 16 } };
        print(matrix);
    }
}

打印结果如下:

1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10 
Process finished with exit code 0

发布了54 篇原创文章 · 获赞 82 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/u011679785/article/details/98184135