LeetCode 54. Spiral Matrix

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].

题意:转圈往里扫,边扫边放到集合里面。

java代码:

 public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> res = new ArrayList<Integer>();

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

        int rowBegin = 0;
        int rowEnd = matrix.length - 1;
        int colBegin = 0;
        int colEnd = matrix[0].length - 1;

        while( rowBegin <= rowEnd && colBegin <= colEnd) {
            //traverse right
            for(int i=colBegin;i<=colEnd;i++)
                res.add(matrix[rowBegin][i]);
            rowBegin++;

            //traverse down
            for(int i=rowBegin;i<=rowEnd;i++)
                res.add(matrix[i][colEnd]);
            colEnd--;

            //traverse left
            if(rowBegin <= rowEnd) {
                for(int i=colEnd;i>=colBegin;i--)
                    res.add(matrix[rowEnd][i]);
                rowEnd--;
            }

            //traverse up
            if(colBegin <= colEnd) {
                for(int i=rowEnd;i>=rowBegin;i--)
                    res.add(matrix[i][colBegin]);
                colBegin++;
            }
        }

        return res;
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容