forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSpiral Matrix II.cpp
56 lines (50 loc) · 1.38 KB
/
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// Runtime: 3 ms (Top 42.85%) | Memory: 6.7 MB (Top 18.22%)
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> vec( n , vector<int> (n, 0));
vector<int>helper;
for(int i=0;i<n*n;i++){
helper.push_back(i+1);
}
int k = 0;
int top = 0;
int down = n-1;
int left = 0;
int right = n-1;
int direction = 0;
vector<int>result;
while(top<=down and left<=right){
if(direction==0){
for(int i=left;i<=right;i++){
vec[top][i] = helper[k];
k++;
}
top++;
}
else if(direction==1){
for(int i=top;i<=down;i++){
vec[i][right] = helper[k];
k++;
}
right--;
}
else if(direction==2){
for(int i=right;i>=left;i--){
vec[down][i] = helper[k];
k++;
}
down--;
}
else if(direction==3){
for(int i=down;i>=top;i--){
vec[i][left] = helper[k];
k++;
}
left++;
}
direction = (direction+1)%4;
}
return vec;
}
};