0
点赞
收藏
分享

微信扫一扫

(每日一练java)螺旋矩阵

晚熟的猫 2022-01-21 阅读 57

螺旋矩阵

给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。

示例 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]

提示:

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 10
  • -100 <= matrix[i][j] <= 100

class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> res = new ArrayList<Integer>();
        if (matrix.length == 0 || (matrix.length == 1 && matrix[0].length == 0))
            return res;
        int left = 0;
        int right = matrix[0].length - 1;
        int top = 0;
        int bottom = matrix.length - 1;
        int num = (right + 1) * (bottom + 1);
        while (num > 0) {
            for (int j = left; j <= right; j++) {
                res.add(matrix[top][j]);
                num--;
            }
            if (num <= 0)
                break;
            top++;
            for (int i = top; i <= bottom; i++) {
                res.add(matrix[i][right]);
                num--;
            }
            if (num <= 0)
                break;
            right--;
            for (int j = right; j >= left; j--) {
                res.add(matrix[bottom][j]);
                num--;
            }
            if (num <= 0)
                break;
            bottom--;
            for (int i = bottom; i >= top; i--) {
                res.add(matrix[i][left]);
                num--;
            }
            if (num <= 0)
                break;
            left++;
        }
        return res;
    }
}

举报

相关推荐

0 条评论