模拟:顺时针打印二维数组

模拟:顺时针打印二维数组


核心思路:定义4个变量分别储存矩阵的四个顶点的横坐标的值,然后根据这个值反复归纳4个顶点的关系。然后把4个顶点“收缩”,进而完成顺时针打印矩阵的全部内容。

public class Main {
	//创建StringBuilder对象ans储存结果
    static StringBuilder ans = new StringBuilder("");
    public static void main(String[] args) {
    	//测试用例
        int[][] arr = new int[][]{
                {1, 2, 3, 4, 9},
                {5, 6, 7, 8, 22},
                {9, 10, 11, 12, 85},
                {13, 14, 15, 16, 66},
                {8, 14, 75, 56, 68},
        };
        printTwoDirectionsArrayByClockwise(arr);;
        System.out.println(ans);
    }

    private static void printTwoDirectionsArrayByClockwise(int[][] arr) {
        int index = 0;
        int a,b,c,d;
        do {
            //取4个顶点的行坐标
            a = index;
            b = arr[0].length - 1 - index;
            c = arr.length - 1 - index;
            d = index;

            //打印第一行
            int upRow = a;
            while (upRow <= b) {
                ans.append(arr[a][upRow++]).append(" ");
                //System.out.print(arr[a][upRow++] + " ");
            }
            //打印右边下面的一行
            int dowCol = a;
            dowCol++;
            while (dowCol <= c) {
                ans.append(arr[dowCol++][c]).append(" ");
                //System.out.print(arr[dowCol++][c] + " ");
            }
            //打印下面到左边的一行
            int downRow = c;
            downRow--;
            while (downRow >= d) {
                ans.append(arr[c][downRow--]).append(" ");
                //System.out.print(arr[c][downRow--] + " ");
            }
            //打印下面的到上面的一行
            int upCol = c;
            upCol--;
            while (upCol > a) {
                ans.append(arr[upCol--][d]).append(" ");
                //System.out.print(arr[upCol--][d] + " ");
            }
            index++;
        } while (a <= b && d < c);
    }

}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值