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

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


核心思路:定义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);
    }

}

猜你喜欢

转载自blog.csdn.net/m0_55418284/article/details/114000255