Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| 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
|
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
39
40
41
42
43
44
45
46
47
48
49
50
51
| class Solution {
public:
enum direction { right, down, left, up };
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> ans(n, vector<int>(n, 0));
int d = right;
int row = 0;
int col = 0;
ans[0][0] = 1;
for (int i = 2; i <= (n * n); i++) {
if (d == right) {
int val = col + 1;
if (val < n && ans[row][val] == 0) {
ans[row][val] = i;
col = val;
} else {
d = down;
i--;
}
} else if (d == down) {
int val = row + 1;
if (val < n && ans[val][col] == 0) {
ans[val][col] = i;
row = val;
} else {
d = left;
i--;
}
} else if (d == left) {
int val = col - 1;
if (val >= 0 && ans[row][val] == 0) {
ans[row][val] = i;
col = val;
} else {
d = up;
i--;
}
} else if (d == up) {
int val = row - 1;
if (val >= 0 && ans[val][col] == 0) {
ans[val][col] = i;
row = val;
} else {
d = right;
i--;
}
}
}
return ans;
}
};
|