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

代码

    public static List<Integer> spiralOrder(int[][] matrix) {

        List<Integer> result = new ArrayList<Integer>();

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

        int startx = 0, endx = matrix.length - 1;
        int starty = 0, endy = matrix[0].length - 1;

        while (startx <= endx && starty <= endy) {

            for (int y = starty; y <= endy; y++) {
                result.add(matrix[startx][y]);
            }

            for (int x = startx + 1; x <= endx; x++) {
                result.add(matrix[x][endy]);
            }

            if (startx == endx || starty == endy) {
                break;
            }

            for (int y = endy - 1; y >= starty; y--) {
                result.add(matrix[endx][y]);
            }

            for (int x = endx - 1; x >= startx + 1; x--) {
                result.add(matrix[x][starty]);
            }

            startx++;
            starty++;
            endx--;
            endy--;
        }

        return result;
    }
阅读更多
版权声明:如果文章有错误,欢迎评论或私信指出,谢谢~ https://blog.csdn.net/Yano_nankai/article/details/49967467
文章标签: leetcode matrix
个人分类: leetcode
所属专栏: LeetCode
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

LeetCode 054 Spiral Matrix

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭