-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path59. Spiral Matrix II
55 lines (45 loc) · 1.16 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
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> ans;
for(int i=0; i<n; i++)
{
vector<int> temp(n);
ans.push_back(temp);
}
int startingRow = 0;
int endingRow = n-1;
int startingCol = 0;
int endingCol = n-1;
int total = (n*n);
int value = 1;
while(value <= total)
{
for(int i=startingCol; i<=endingCol; i++)
{
ans[startingRow][i] = value;
value++;
}
startingRow++;
for(int i=startingRow; i<=endingRow; i++)
{
ans[i][endingCol] = value;
value++;
}
endingCol--;
for(int i=endingCol; i>=startingCol; i--)
{
ans[endingRow][i] = value;
value++;
}
endingRow--;
for(int i=endingRow;i>=startingRow; i--)
{
ans[i][startingCol] = value;
value++;
}
startingCol++;
}
return ans;
}
};