您的位置:首页 > 其它

LeetCode 059 Spiral Matrix II

2015-11-22 11:36 302 查看

题目描述

Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

For example,

Given n = 3,

You should return the following matrix:

[

[ 1, 2, 3 ],

[ 8, 9, 4 ],

[ 7, 6, 5 ]

]

代码

[code]    public static int[][] generateMatrix(int n) {

        if (n <= 0) {
            return new int[0][0];
        }

        int[][] matrix = new int

;

        int num = 1;

        int startx = 0, endx = n - 1;
        int starty = 0, endy = n - 1;

        while (startx <= endx && starty <= endy) {
            for (int y = starty; y <= endy; y++) {
                matrix[startx][y] = num++;
            }

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

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

            for (int y = endy - 1; y >= starty; y--) {
                matrix[endx][y] = num++;
            }

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

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

        return matrix;
    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: