leetcode-54. Spiral Matrix(打印蛇形矩阵)

来源:互联网 发布:720全景图制作软件 编辑:程序博客网 时间:2024/06/02 03:32

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

For example,
Given the following matrix:

[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
You should return [1,2,3,6,9,8,7,4,5].

代码如下:

public class Solution {    public List<Integer> spiralOrder(int[][] matrix) {        List<Integer> result=new ArrayList<>();        if(matrix.length==0)return result;        int rs=0;        int cs=0;        int re=matrix.length-1;        int ce=matrix[0].length-1;        while(rs<=re && cs<=ce)        {            for(int i=cs;i<=ce;++i)            {                result.add(matrix[rs][i]);             }            rs++;            for(int i=rs;i<=re;++i)            {                result.add(matrix[i][ce]);            }            ce--;            if(rs<=re)            {                   for(int i=ce;i>=cs;i--)                {                    result.add(matrix[re][i]);                }              }            re--;            if(cs<=ce)            {                for(int i=re;i>=rs;i--)                {                    result.add(matrix[i][cs]);                }            }            cs++;        }        return result;    }}
原创粉丝点击