-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathSpiralStorage.java
49 lines (40 loc) · 1.19 KB
/
SpiralStorage.java
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
/*https://leetcode.com/problems/spiral-matrix-ii/*/
class Solution
{
public int[][] generateMatrix(int n)
{
int[][] matrix = new int[n][n];
int rs = 0, re = n-1, cs = 0, ce = n-1;
int element = 1;
int i = 0, j = 0;
//till we have more elements
while (rs <= re && cs <= ce)
{
//add the top row
for (j = cs; j <= ce; ++j)
if (matrix[i][j] == 0)
matrix[i][j] = element++;
//delete top row
++rs; --j;
//add right column
for (i = rs; i <= re; ++i)
if (matrix[i][j] == 0)
matrix[i][j] = element++;
//delete right column
--ce; --i;
//add bottom row
for (j = ce; j >= cs; --j)
if (matrix[i][j] == 0)
matrix[i][j] = element++;
//delete bottom row
--re; ++j;
//add left column
for (i = re; i >= rs; --i)
if (matrix[i][j] == 0)
matrix[i][j] = element++;
//delete left column
++cs; ++i;
}
return matrix;
}
}