forked from Ritesh25696/interviewBit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSpiral Order Matrix II
53 lines (46 loc) · 1.36 KB
/
Spiral Order Matrix II
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
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
Example:
Given n = 3,
You should return the following matrix:
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
**********************************************************************************************************
vector<vector<int> > Solution::generateMatrix(int num) {
vector<vector<int>> A(num, vector<int>(num, 0));
int top = 0 , bottom = A.size()-1, left = 0 , right = A[0].size()-1 , dir =0 ;
int n = 1;
while(top<=bottom && left<=right){
if(dir == 0){
for(int i=left ; i<=right ; i++){
A[top][i] = n;
n++;
}
top++;
dir = 1;
}
else if(dir == 1){
for(int i=top ; i<=bottom ; i++){
A[i][right] = n;
n++;
}
right--;
dir = 2;
}
else if (dir == 2){
for(int i=right ; i >= left ; i--){
A[bottom][i] = n;
n++;
}
bottom--;
dir = 3;
}
else{
for(int i=bottom; i>= top ; i--){
A[i][left] = n;
n++;
}
left++;
dir = 0;
}
}
return A;
}