顺时针打印矩阵

顺时针打印矩阵

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。

示例 1:

输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]

示例 2:

输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]

public List spiralOrder(int[][] matrix) {
    int left = 0, right = matrix[0].length - 1;
    int top = 0, bottom = matrix.length - 1;
    List res = new ArrayList<>();
    int size = matrix.length * matrix[0].length;
    while (true) {
        for (int i = left; i <= right; i++) {
            res.add(matrix[top][i]);
        }
        top++;
        if (res.size() == size) {
            break;
        }
        for (int i = top; i <= bottom; i++) {
            res.add(matrix[i][right]);
        }
        right--;
        if (res.size() == size) {
            break;
        }
        for (int i = right; i >= left; i--) {
            res.add(matrix[bottom][i]);
        }
        bottom--;
        if (res.size() == size) {
            break;
        }
        for (int i = bottom; i >= top; i--) {
            res.add(matrix[i][left]);
        }
        left++;
        if (res.size() == size) {
            break;
        }
    }
    return res;
}

螺旋矩阵 II

给你一个正整数 n ,生成一个包含 1n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix

示例 1:

输入:n = 3
输出:[[1,2,3],[8,9,4],[7,6,5]]

示例 2:

输入:n = 1
输出:[[1]]

public int[][] generateMatrix(int n) {
    int all = n * n;
    int[][] res = new int[n][n];
    int k = 0;
    int left = 0, right = n - 1, top = 0, bottom = n - 1;
    while (left <= right && top <= bottom) {
        if (k < all) {
            for (int i = left; i <= right; i++) {
                res[top][i] = ++k;
            }
            top++;
        }
        if (k < all) {
            for (int i = top; i <= bottom; i++) {
                res[i][right] = ++k;
            }
            right--;
        }
        if (k < all) {
            for (int i = right; i >= left; i--) {
                res[bottom][i] = ++k;
            }
            bottom--;
        }
        if (k < all) {
            for (int i = bottom; i >= top; i--) {
                res[i][left] = ++k;
            }
            left++;
        }
    }
    return res;
}

你可能感兴趣的:(顺时针打印矩阵)