-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy path59. Spiral Matrix II
60 lines (44 loc) · 1.38 KB
/
59. Spiral 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
54
55
56
57
58
59
60
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
// creating a vector of n*n
vector<vector<int>> ans(n, vector<int>(n, 0));
//int row=matrix.size();
//int col =matrix[0].size();
int count =0;
int total =n*n;
//// all index
int startingrow=0;
int startingcol=0;
int endingrow=n-1;
int endingcol=n-1;
while(count<total)
{
for(int i=startingcol;count<total && i<=endingcol; i++)
{
count++;
ans[startingrow][i]=count;
}
startingrow++;
for(int i=startingrow;count<total && i<=endingrow; i++)
{
count++;
ans[i][endingcol]=count;
}
endingcol--;
for(int i=endingcol;count<total && i>=startingcol; i--)
{
count++;
ans[endingrow][i]=count;
}
endingrow--;
for(int i=endingrow;count<total && i>=startingrow; i--)
{
count++;
ans[i][startingcol]=count;
}
startingcol++;
}
return ans;
}
};