顺时针打印二维数组---执行判断

将一个二维数组顺时针进行打印,如图所示,
1,2,3,4
5,6,7,8
9,10,11,12
13,14,15,16
打印出来是:1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10。

思路:打印分为四步:从左到右,从上到下,从右到左,从下到上。第一步是肯定会执行的,到达列数时开始执行第二步,第二步能够执行的条件终止行号大于起始行号,第三步打印的前提条件是圈内至少有两行两列,也就是说除了要求终止行号大于起始行号之外,还要求终止列号大于起始列号,需要打印第四步的前提条件是至少有三行两列,因此要求终止行号比起始行号至少大 2,同时终止列号大于起始列号。

java代码:

public class shunshizhendayin {

    private static void meiyiquan(int[][] nums) {
        if (nums == null)
            return;
        int rows = nums.length;
        int columns = nums[0].length;
        int start = 0;
        while (start * 2 < rows && start * 2 < columns) {
            shunshidayin(nums, start);
            start++;
        }
    }

    private static void shunshidayin(int[][] a, int start) {
        int endx = a[0].length - start - 1;// 右边界
        int endy = a.length - 1 - start;// 下边界

        // 打印最上面的行
        for (int i = start; i <= endx; i++) {
            System.out.print(a[start][i] + "\t");
        }

        // 从上到下打印
        if (start < endy) {
            for (int i = start + 1; i <= endy; i++) {
                System.out.print(a[i][endx]+ "\t");
            }
        }

        // 从右向左打印
        if (start < endx && start < endy) {
            for (int i = endx - 1; i >= start; i--) {
                System.out.print(a[endy][i]+ "\t");
            }
        }

        // 从下到上打印
        if (start < endx && start < endy - 1) {
            for (int i = endy - 1; i >= start + 1; i--) {
                System.out.print(a[i][start]+ "\t");
            }
        }

    }

    public static void main(String[] args) {
        int[][] tes = { { 1, 2, 3,  },
                { 4, 5, 6},
                { 7, 8, 9 },
                 };
        meiyiquan(tes);
    }

}

你可能感兴趣的:(数据结构和算法,二维数组)