蛇形转圈打印矩阵

版权声明:转载请注明 https://blog.csdn.net/qq_34115899/article/details/82936408

给定一个整型矩阵arr,按照转圈的方式打印

比如

输入:

4 4 
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

输入:

4 4
 1   2   3  4
12 13 14 5
11 16 15 6
10  9   8  7
输出:1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 

要求:额外的空间复杂度为O(1)

思路参考左程云,矩阵分圈处理方式。在矩阵中用左上角的坐标(startX, startY)和右下角的坐标(endX, endY)就可以表示一个子矩阵,比如例子中的矩阵,当(startX, startY)=(0, 0)时、(endX, endY)=(3, 3)时,表示的子矩阵就是整个矩阵,这个子矩阵的最外层如下:

   1    2    3     4

   5                 8

   9                12

   13  14  15  16

如果能把这个子矩阵的外层转圈打印出来,那么就把startX, startY加1, 即(startX, startY) = (1, 1), 再把endX, endY减1,即(endX, endY) = (2, 2),此时表示子矩阵如下

   6     7

  10   11

将这个子矩阵转圈打印出来,接着把startX, startY加1, 即(startX, startY) = (2, 2), 再把endX, endY减1,即(endX, endY) = (1, 1),如果发现左上角坐标跑到了右下角坐标的右方或下方,整个过程就停止了。

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        int row = cin.nextInt();
        int col = cin.nextInt();
        int[][] arr = new int[row][col];
        for (int i = 0; i < row; ++i) {
            for (int j = 0; j < col; ++j) {
                arr[i][j] = cin.nextInt();
            }
        }
        cin.close();
        orderPrint(arr);
    }

    private static void orderPrint(int[][] arr) {
        int startX = 0, startY = 0;
        int endX = arr.length - 1, endY = arr[0].length - 1;
        while (startX <= endX && startY <= endY) {
            print(arr, startX++, startY++, endX--, endY--);
        }
    }

    private static void print(int[][] arr, int startX, int startY, int endX, int endY) {
        if (startX == endX) { // 子矩阵只有一行
            for (int i = startY; i <= endY; ++i) {
                System.out.print(arr[startX][i] + " ");
            }
        } else if (startY == endY) { // 子矩阵只有一列
            for (int i = startX; i <= endX; ++i) {
                System.out.print(arr[i][startY] + " ");
            }
        } else {
            int curX = startX;
            int curY = startY;
            while (curY != endY) {
                System.out.print(arr[startX][curY++] + " ");
            }
            while (curX != endX) {
                System.out.print(arr[curX++][endY] + " ");
            }
            while (curY != startY) {
                System.out.print(arr[endX][curY--] + " ");
            }
            while (curX != startX) {
                System.out.print(arr[curX--][startY] + " ");
            }
        }
    }
}

==========================Talk is cheap, show me the code=======================

猜你喜欢

转载自blog.csdn.net/qq_34115899/article/details/82936408