forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSpiralMatrixII.java
More file actions
53 lines (41 loc) · 1.27 KB
/
SpiralMatrixII.java
File metadata and controls
53 lines (41 loc) · 1.27 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
53
/**
* Spiral Matrix II
* Generates an n x n matrix filled with numbers from 1 to n^2 in spiral order.
*
* @see <a href="https://leetcode.com/problems/spiral-matrix-ii/">LeetCode – Spiral Matrix II</a>
* @see <a href="https://en.wikipedia.org/wiki/Spiral_matrix">Wikipedia – Spiral Matrix</a>
*/
package com.thealgorithms.matrix;
public class SpiralMatrixII {
public int[][] generateMatrix(int n) {
int[][] matrix = new int[n][n];
int top = 0;
int bottom = n - 1;
int left = 0;
int right = n - 1;
int num = 1;
while (top <= bottom && left <= right) {
for (int i = left; i <= right; i++) {
matrix[top][i] = num++;
}
top++;
for (int i = top; i <= bottom; i++) {
matrix[i][right] = num++;
}
right--;
if (top <= bottom) {
for (int i = right; i >= left; i--) {
matrix[bottom][i] = num++;
}
bottom--;
}
if (left <= right) {
for (int i = bottom; i >= top; i--) {
matrix[i][left] = num++;
}
left++;
}
}
return matrix;
}
}