0059. Spiral Matrix II

https://leetcode.com/problems/spiral-matrix-ii

Description

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

Example 1:

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

Example 2:

**Input:** n = 1
**Output:** [[1]]

Constraints:

  • 1 <= n <= 20

ac

// no special knowledge, just spacial imagination, be careful, writing codes by looking at sample

class Solution {
    public int[][] generateMatrix(int n) {
        int[][] res = new int[n][n];
        // corner case
        if (n == 0) return res;

        // rb, re, cb, ce
        int rb = 0, re = n - 1, cb = 0, ce = n - 1;
        int num = 1;
        while (rb <= re) {
            // final one
            if (rb == re) res[rb][rb] = num;
            // top
            for (int c = cb; c < ce; c++) {
                res[rb][c] = num;
                num++;
            }
            // right
            for (int r = rb; r < re; r++) {
                res[r][ce] = num;
                num++;
            }
            // buttom
            for (int c = ce; c > cb; c--) {
                res[re][c] = num;
                num++;
            }
            // left
            for (int r = re ; r > rb; r--) {
                res[r][cb] = num;
                num++;
            }
            rb++;
            re--;
            cb++;
            ce--;
        }
        return res;
    }
}

Last updated