-
Notifications
You must be signed in to change notification settings - Fork 0
/
59. Spiral Matrix II.cpp
29 lines (26 loc) · 1015 Bytes
/
59. Spiral Matrix II.cpp
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
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> result (n, vector<int>(n));
int cnt = 1;
for (int layer = 0; layer < (n + 1) / 2; ++layer) {
// direction 1 - traverse from left to right
for (int ptr = layer; ptr < n - layer; ++ptr) {
result[layer][ptr] = cnt++;
}
// direction 2 - traverse from top to bottom
for (int ptr = layer + 1; ptr < n - layer; ++ptr) {
result[ptr][n - layer - 1] = cnt++;
}
// direction 3 - traverse from right to left
for (int ptr = n - layer - 2; ptr >= layer; --ptr) {
result[n - layer - 1][ptr] = cnt++;
}
// direction 4 - traverse from bottom to top
for (int ptr = n - layer - 2; ptr > layer; --ptr) {
result[ptr][layer] = cnt++;
}
}
return result;
}
};