前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >54. 螺旋矩阵

54. 螺旋矩阵

作者头像
张伦聪zhangluncong
发布2022-10-26 17:53:08
2400
发布2022-10-26 17:53:08
举报

给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。

示例 1:

代码语言:javascript
复制
输入:
[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]
输出: [1,2,3,6,9,8,7,4,5]

示例 2:

代码语言:javascript
复制
输入:
[
  [1, 2, 3, 4],
  [5, 6, 7, 8],
  [9,10,11,12]
]
输出: [1,2,3,4,8,12,11,10,9,5,6,7]

解:

代码语言:javascript
复制
   public List<Integer> spiralOrder(int[][] matrix) {

        List<Integer> linkedList = new LinkedList<>();

        if (matrix == null || matrix.length == 0) {
            return linkedList;
        }

        //左右上下四个边界
        int left = 0;
        int right = matrix[0].length - 1;
        int top = 0;
        int bottom = matrix.length - 1;

        int i;
        while (true) {

            //上边,自左至右
            for (i = left; i <= right; i++) {
                linkedList.add(matrix[top][i]);
            }
            if (++top > bottom) {
                break;
            }

            //右边,自上至下
            for (i = top; i <= bottom; i++) {
                linkedList.add(matrix[i][right]);
            }
            if (left > --right) {
                break;
            }

            //下边,自右至左
            for (i = right; i >= left; i--) {
                linkedList.add(matrix[bottom][i]);
            }
            if (top > --bottom) {
                break;
            }

            //左边,自下至上
            for (i = bottom; i >= top; i--) {
                linkedList.add(matrix[i][left]);
            }
            if (++left > right) {
                break;
            }

        }

        return linkedList;
    }
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018-06-03,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档