-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleetcode_59.cpp
More file actions
38 lines (31 loc) · 1.15 KB
/
Copy pathleetcode_59.cpp
File metadata and controls
38 lines (31 loc) · 1.15 KB
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:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> arr(n, vector<int>(n, 0)); // 초기화
int top = 0, bottom = n - 1, left = 0, right = n - 1;
int index = 1; // 숫자는 1부터 시작
while (left <= right && top <= bottom) {
for (int i = left; i <= right; i++) { // → 방향
arr[top][i] = index++;
}
top++;
for (int i = top; i <= bottom; i++) { // ↓ 방향
arr[i][right] = index++;
}
right--;
if (top <= bottom) { // ← 방향
for (int i = right; i >= left; i--) {
arr[bottom][i] = index++;
}
bottom--;
}
if (left <= right) { // ↑ 방향
for (int i = bottom; i >= top; i--) {
arr[i][left] = index++;
}
left++;
}
}
return arr;
}
};