-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy path59. Spiral Matrix II.cpp
44 lines (44 loc) · 1.15 KB
/
59. 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
/*Spiral Matrix II:Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.*/
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int> > matrix(n,vector<int>(n,0));
if(n <= 0){
return matrix;
}
int count = n * n;
int index = 1;
int x = 0,y = -1;
while(index <= count){
// right
++y;
while(y < n && matrix[x][y] == 0){
matrix[x][y++] = index;
++index;
}
--y;
// down
++x;
while(x < n && matrix[x][y] == 0){
matrix[x++][y] = index;
++index;
}
--x;
// left
--y;
while(y >= 0 && matrix[x][y] == 0){
matrix[x][y--] = index;
++index;
}
++y;
// up
--x;
while(x >= 0 && matrix[x][y] == 0){
matrix[x--][y] = index;
++index;
}
++x;
}
return matrix;
}
};