数据结构与算法(Java) 22:转圈打印矩阵

题目 给定一个整型矩阵matrix,请按照转圈的方式打印它。 例如:

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

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

思路 递归地一圈一圈打印。

package algorithm.section4;

public class PrintMatrixSpiralOrder {
    public static void printMatrix(int[][] matrix){
        int top = 0;
        int bottom = matrix.length - 1;
        int left = 0;
        int right = matrix[0].length - 1;

        while (top <= bottom && left <= right)
            printEdge(matrix, top++, bottom--, left++, right--);
    }

    public static void printEdge(int[][] matrix, int top, int bottom, int left, int right){
        if (top < bottom && left < right){
            for (int i = left; i < right; i++) System.out.print(matrix[top][i] + " ");
            for (int i = top; i < bottom; i++) System.out.print(matrix[i][right] + " ");
            for (int i = right; i > left; i--) System.out.print(matrix[bottom][i] + " ");
            for (int i = bottom; i > top; i--) System.out.print(matrix[i][left] + " ");
        } else if (top < bottom) {
            for (int i = top; i <= bottom; i++) System.out.print(matrix[i][left] + " ");
        } else {
            for (int i = left; i <= right; i++) System.out.print(matrix[top][i] + " ");
        }
    }

    public static void main(String[] args){
        int[][] matrix = {
                { 1, 2, 3, 4 },
                { 5, 6, 7, 8 },
                { 9, 10, 11, 12 },
                { 13, 14, 15, 16 }
        };
        printMatrix(matrix);
    }
}
发布了149 篇原创文章 · 获赞 36 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/Dorothy_Xue/article/details/105647714