-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.cs
More file actions
41 lines (41 loc) · 1017 Bytes
/
Solution.cs
File metadata and controls
41 lines (41 loc) · 1017 Bytes
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
public class Solution
{
public int[][] GenerateMatrix(int n)
{
int[][] ret = new int[n][];
for (int i = 0; i < n; i++)
{
ret[i] = new int[n];
}
int minR = 0, maxR = n - 1, minC = 0, maxC = n - 1;
int val = 1;
while (minR <= maxR && minC <= maxC)
{
// left -> right
for (int i = minC; i <= maxC; i++)
{
ret[minR][i] = val++;
}
minR++;
// top -> bottom
for (int i = minR; i <= maxR; i++)
{
ret[i][maxC] = val++;
}
maxC--;
// right -> left
for (int i = maxC; i >= minC; i--)
{
ret[maxR][i] = val++;
}
maxR--;
// bottom -> top
for (int i = maxR; i >= minR; i--)
{
ret[i][minC] = val++;
}
minC++;
}
return ret;
}
}