LeetCode_54.螺旋矩阵

题目:
给定一个包含 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]
图解:
在这里插入图片描述
代码实现

class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        ArrayList<Integer> list=new  ArrayList<Integer>();  //定义一个链表
        if(matrix==null||matrix.length==0){
            return list;
        }
        int row=matrix.length;      //定义矩阵的行数
        int col=matrix[0].length;   //定义矩阵的列数
        
        boolean[][] status=new boolean[row][col];   //定义一个标记状态
        int x=0;                    //定义初始数字行的位置
        int y=0;
        int len=row*col;                        //矩阵的总长度
        while(true){
            if(list.size()==len){             //如果链表长度等于矩阵的长度则退出循环
                break;
            }
            //向右
            while(y<col&&!status[x][y]&&list.size()<len){
                list.add(matrix[x][y]);
                status[x][y]=true;              //把添加到链表的元素标记为true
                y++;                            //y角标右移
            }
                y--;                            //跳出循环时y已经更新在数组外(右边)所以进入下一次循环前把y向左移回来
                x++;                            //x进入下一行
            //向下
            while(x<row&&!status[x][y]&&list.size()<len){
                list.add(matrix[x][y]);
                status[x][y]=true;  
                x++;                            //x角标下移
            }
                x--;                            //更新x的位置
                y--;                            //y进入左面那一列
            //向左
              while(y>=0&&!status[x][y]&&list.size()<len){
                list.add(matrix[x][y]);
                status[x][y]=true;  
                y--;                            //y角标左移
            }
                y++;                            //更新y的位置
                x--;                            //x进入上一行
            //向上
              while(x>=0&&!status[x][y]&&list.size()<len){
                list.add(matrix[x][y]);
                status[x][y]=true;  
                x--;                            //x角标上移
            }
                x++;                            //更新x的位置
                y++;                            //y进入下一列
        }
        return list;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_44561640/article/details/89099987