-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSpiral Matrix II.cpp
51 lines (50 loc) · 1.21 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
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
if(n == 1)
return {{1}};
vector<vector<int>> matrix(n, vector<int> (n));
int dir = 0, i, T = 0, B = n - 1, L = 0, R = n - 1, val = 1;
while(T <= B && L <= R)
{
if(dir == 0)
{
for(i = L; i <= R; i++)
{
matrix[T][i] = val;
val++;
}
T++;
}
if(dir == 1)
{
for(i = T; i <= B; i++)
{
matrix[i][R] = val;
val++;
}
R--;
}
if(dir == 2)
{
for(i = R; i >= L; i--)
{
matrix[B][i] = val;
val++;
}
B--;
}
if(dir == 3)
{
for(i = B; i >= T; i--)
{
matrix[i][L] = val;
val++;
}
L++;
}
dir = (dir + 1) % 4;
}
return matrix;
}
};