-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSpiral Matrix II
More file actions
40 lines (40 loc) · 1.06 KB
/
Spiral Matrix II
File metadata and controls
40 lines (40 loc) · 1.06 KB
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
public class Solution {
public int[][] generateMatrix(int n) {
// Note: The Solution object is instantiated only once and is reused by each test case.
int[][] result = new int[n][n];
if(n == 0) return result;
if(n == 1 || n == -1)
{
result[0][0] = 1;
return result;
}
int count = 1;
int mid = (int)Math.floor(n/2);
for(int i=0; i<mid; i++)
{
for(int j=i; j<n-1-i; j++)
{
result[i][j] = count;
count++;
}
for(int j=i; j<n-1-i; j++)
{
result[j][n-1-i] = count;
count++;
}
for(int j=i; j<n-1-i; j++)
{
result[n-1-i][n-1-j] = count;
count++;
}
for(int j=i; j<n-1-i; j++)
{
result[n-1-j][i] = count;
count++;
}
}
if((n%2) != 0)
result[mid][mid] = n*n;
return result;
}
}