• 螺旋矩阵


    给定一个包含 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

  • 相关阅读:
    ARP投毒攻击
    sniffer简单使用
    MAC泛洪攻击
    又是一题反序列化了解一下???
    关于parse_str变量覆盖分析
    超级ping(多线程版)
    文本输入框input将输入转换为统一大小写
    通俗易懂JSONP讲解
    通俗易懂JSONP讲解
    Fastjson主要接口和类库说明
  • 原文地址:https://www.cnblogs.com/wuyouwei/p/11994275.html
Copyright © 2020-2023  润新知