59. Spiral Matrix II

59. Spiral Matrix II

Description

Difficulty: Medium

Related Topics: Array, Matrix, Simulation

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

Example 1:

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

Example 2:

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

Constraints:

  • 1 <= n <= 20

Hints/Notes

  • Traverse the four sides in one iteration

Solution

Language: C++

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
class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int>> res(n, vector<int>(n, 0));
        if (n == 0return res;
        int left = 0, right = n - 1, up = 0, down = n - 1, val = 1;
        while (val <= n * n) {
            if (up <= down) {
                for (int i = left; i <= right; i++) {
                    res[up][i] = val++;
                }
                up++;
            }
            if (left <= right) {
                for (int i = up; i <= down; i++) {
                    res[i][right] = val++;
                }
                right--;
            }
            if (up <= down) {
                for (int i = right; i >= left; i--) {
                    res[down][i] = val++;
                }
                down--;
            }
            if (left <= right) {
                for (int i = down; i >= up; i--) {
                    res[i][left] = val++;
                }
                left++;
            }
        }
        return res;
    }
};