[LeetCode] 59. Spiral Matrix II

Problem

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

Example:

Input: 3
Output:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]

Solution

class Solution {
    public int[][] generateMatrix(int n) {
        int[][] res = new int[n][n];
        if (n == 0) return res;
        int num = 1, rStart = 0, rEnd = n-1, cStart = 0, cEnd = n-1;
        while (rStart <= rEnd && cStart <= cEnd) {
            for (int j = cStart; j <= cEnd; j++) res[rStart][j] = num++;
            rStart++;
            for (int i = rStart; i <= rEnd; i++) res[i][cEnd] = num++;
            cEnd--;
            for (int j = cEnd; j >= cStart; j--) {
                if (rStart > rEnd) break;
                res[rEnd][j] = num++;
            }
            rEnd--;
            for (int i = rEnd; i >= rStart; i--) {
                if (cStart > cEnd) break;
                res[i][cStart] = num++;
            } 
            cStart++;
        }
        return res;
    }
}
阅读 557

推荐阅读
Road to Glory
用户专栏

對酒當歌,人生幾何?譬如朝露,去日苦多。

22 人关注
639 篇文章
专栏主页