首页 > 其他 > 详细

螺旋矩阵

时间:2019-12-06 12:24:08      阅读:78      评论:0      收藏:0      [点我收藏+]

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

示例 1:

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

输入:
[
[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<Integer> spiralOrder(int[][] matrix){
        List<Integer> res=new ArrayList<>();
        if(matrix.length==0){
            return res;
        }
        /*上边界*/
        int top=0;
        /*下边界*/
        int bottom=matrix.length-1;
        /*左边界*/
        int left=0;
        /*右边界*/
        int right=matrix[0].length-1;
        while (true){
            /*向右移动*/
            for(int j=left;j<=right;j++){
                res.add(matrix[top][j]);
            }
            /*上边界+1*/
            if(++top>bottom){
                break;
            }
            /*向下移动*/
            for(int j=top;j<=bottom;j++){
                res.add(matrix[j][right]);
            }
            /*右边界-1*/
            if(--right<left){
                break;
            }
            /*向左移动*/
            for(int j=right;j>=left;j--){
                res.add(matrix[bottom][j]);
            }
            /*下边界-1*/
            if(--bottom<top){
                break;
            }
            /*向上移动*/
            for(int j=bottom;j>=top;j--){
                res.add(matrix[j][left]);
            }
            /*左边界+1*/
            if(++left>right){
                break;
            }

        }
        return res;
    }
View Code

 

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/spiral-matrix

螺旋矩阵

原文:https://www.cnblogs.com/wuyouwei/p/11994275.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!