-
Notifications
You must be signed in to change notification settings - Fork 0
/
LC59.cpp
38 lines (38 loc) · 1.04 KB
/
LC59.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
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<int> row(n,0);
vector<vector<int>> result(n,row);
int num=1,rowstart=0,rowend=n-1,colstart=0,colend=n-1;
while(rowstart<=rowend && colstart<=colend)
{
for(int j=colstart;j<=colend;j++)
{
result[rowstart][j]=num;
num++;
}
rowstart++;
for(int i=rowstart;i<=rowend;i++)
{
result[i][colend]=num;
num++;
}
colend--;
if(rowstart<=rowend)
for(int j=colend;j>=colstart;j--)
{
result[rowend][j]=num;
num++;
}
rowend--;
if(colstart<=colend)
for(int i=rowend;i>=rowstart;i--)
{
result[i][colstart]=num;
num++;
}
colstart++;
}
return result;
}
};