关闭

LeetCode 054 Spiral Matrix

标签: leetcodematrix
270人阅读 评论(0) 收藏 举报
分类:

题目描述

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;
    }
1
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:132254次
    • 积分:4004
    • 等级:
    • 排名:第7813名
    • 原创:246篇
    • 转载:0篇
    • 译文:0篇
    • 评论:37条
    博客专栏
    LeetCode

    文章:80篇

    阅读:29366
    最新评论