-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSolution.java
More file actions
52 lines (50 loc) · 1.37 KB
/
Copy pathSolution.java
File metadata and controls
52 lines (50 loc) · 1.37 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
41
42
43
44
45
46
47
48
49
50
51
52
public class Solution
{
public int[][] generateMatrix(int n)
{
if (n <= 0)
{
return new int[][]{{}};
}
int[][] matrix = new int[n][n];
generateSpiralMatrix(0, 0, matrix.length - 1, matrix[0].length - 1, matrix, 1);
return matrix;
}
private void generateSpiralMatrix(int minRow, int minCol, int maxRow, int maxCol, int[][] matrix, int next)
{
if (minRow > maxRow || minCol > maxCol)
{
return;
}
if (minRow <= maxRow && minCol <= maxCol)
{
for (int i = minCol; i <= maxCol; i++)
{
matrix[minRow][i] = next++;
}
minRow++;
for (int i = minRow; i <= maxRow; i++)
{
matrix[i][maxCol] = next++;
}
maxCol--;
if (minRow <= maxRow)
{
for (int i = maxCol; i >= minCol; i--)
{
matrix[maxRow][i] = next++;
}
}
maxRow--;
if (minCol <= maxCol)
{
for (int i = maxRow; i >= minRow; i--)
{
matrix[i][minCol] = next++;
}
}
minCol++;
generateSpiralMatrix(minRow, minCol, maxRow, maxCol, matrix, next);
}
}
}