-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSpiral_order_matrix_II.cpp
More file actions
43 lines (43 loc) · 1.11 KB
/
Spiral_order_matrix_II.cpp
File metadata and controls
43 lines (43 loc) · 1.11 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
39
40
41
42
43
vector<vector<int> > Solution::generateMatrix(int A) {
vector<vector<int>> grid(A,vector<int>(A,0));
if (A==0)
return grid;
int top = 0, bottom = A-1, left = 0, right = A-1;
int direction = 1;
int element = 1;
while (top<=bottom && left<=right){
if (direction==1){
for(int i=left;i<=right;i++){
grid[top][i] = element;
element++;
}
top++;
direction = 2;
}
else if(direction==2){
for(int i=top;i<=bottom;i++){
grid[i][right] = element;
element++;
}
right--;
direction = 3;
}
else if(direction==3){
for(int i=right;i>=left;i--){
grid[bottom][i] = element;
element++;
}
bottom--;
direction = 4;
}
else{
for(int i=bottom;i>=top;i--){
grid[i][left] = element;
element++;
}
left++;
direction = 1;
}
}
return grid;
}