[LeetCode] 59. Spiral Matrix II

Problem

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

Example:

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

Explanation

  1. Similar to 54. Spiral Matrix, we create top, right, bottom, left variables. Then create a counter starts from 1, fill the matrix. When top == bottom or left == right, since it’s a square matrix, we check if input n is an odd number or not. If it’s event, then we are done. If it’s odd, there’s a middle element, and the middle element position will be matrix[n/2][n/2], so we fill it with the counter. Finally return the filled matrix.

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class Solution {
    public int[][] generateMatrix(int n) {
        int[][] res = new int[n][n];
        if (n <= 0) return res;
        
        int top = 0;
        int right = res[0].length-1;
        int bottom = res.length-1;
        int left = 0;
        
        int counter = 1;
        while (top < bottom && left < right) {
            for (int i = left; i < right; i++) {
                res[top][i] = counter++;
            }
            for (int i = top; i < bottom; i++) {
                res[i][right] = counter++;
            }
            for (int i = right; i > left; i--) {
                res[bottom][i] = counter++;
            }
            for (int i = bottom; i > top; i--) {
                res[i][left] = counter++;
            }
            top++;
            right--;
            bottom--;
            left++;
        }
        if (n % 2 == 1) {
            int midA = n / 2;
            int midB = n / 2;
            res[midA][midB] = counter;
        }
        
        return res;
    }
}