-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSpiral Matrix II.cpp
68 lines (39 loc) · 1.07 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
57
58
59
60
61
62
63
64
65
66
67
68
PROBLEM:
Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order.
Example 1:
Input: n = 3
Output: [[1,2,3],[8,9,4],[7,6,5]]
Example 2:
Input: n = 1
Output: [[1]]
Constraints:
1. 1 <= n <= 20
SOLUTION:
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
int i,l1,l2,r1,r2,c;
vector<vector<int>> v(n,vector<int>(n));
l1=0;
l2=n-1;
r1=0;
r2=n-1;
c=1;
while(l1<=l2 && r1<=r2)
{
for(i=l1;i<=l2;i++) //left to right
v[r1][i]=c++;
for(i=r1+1;i<=r2;i++) //top to down
v[i][l2]=c++;
for(i=l2-1;i>=l1;i--) //right to left
v[r2][i]=c++;
for(i=r2-1;i>r1;i--) //down to top
v[i][l1]=c++;
l1++;
l2--;
r1++;
r2--;
}
return v;
}
};