Skip to content

Commit 2970424

Browse files
committed
Add Spiral Matrix II algorithm
1 parent 0f9139d commit 2970424

File tree

2 files changed

+80
-0
lines changed

2 files changed

+80
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package com.thealgorithms.matrix;
2+
3+
public class SpiralMatrixII {
4+
5+
public int[][] generateMatrix(int n) {
6+
7+
int[][] matrix = new int[n][n];
8+
9+
int top = 0, bottom = n - 1;
10+
int left = 0, right = n - 1;
11+
12+
int num = 1;
13+
14+
while (top <= bottom && left <= right) {
15+
16+
for (int i = left; i <= right; i++) {
17+
matrix[top][i] = num++;
18+
}
19+
top++;
20+
21+
for (int i = top; i <= bottom; i++) {
22+
matrix[i][right] = num++;
23+
}
24+
right--;
25+
26+
if (top <= bottom) {
27+
for (int i = right; i >= left; i--) {
28+
matrix[bottom][i] = num++;
29+
}
30+
bottom--;
31+
}
32+
33+
if (left <= right) {
34+
for (int i = bottom; i >= top; i--) {
35+
matrix[i][left] = num++;
36+
}
37+
left++;
38+
}
39+
}
40+
41+
return matrix;
42+
}
43+
}
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package com.thealgorithms.matrix;
2+
3+
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
4+
5+
import org.junit.jupiter.api.Test;
6+
7+
class SpiralMatrixIITest {
8+
9+
private final SpiralMatrixII spiral = new SpiralMatrixII();
10+
11+
@Test
12+
void testNEquals1() {
13+
int[][] expected = {{1}};
14+
assertArrayEquals(expected, spiral.generateMatrix(1));
15+
}
16+
17+
@Test
18+
void testNEquals3() {
19+
int[][] expected = {
20+
{1, 2, 3},
21+
{8, 9, 4},
22+
{7, 6, 5}
23+
};
24+
assertArrayEquals(expected, spiral.generateMatrix(3));
25+
}
26+
27+
@Test
28+
void testNEquals4() {
29+
int[][] expected = {
30+
{1, 2, 3, 4},
31+
{12, 13, 14, 5},
32+
{11, 16, 15, 6},
33+
{10, 9, 8, 7}
34+
};
35+
assertArrayEquals(expected, spiral.generateMatrix(4));
36+
}
37+
}

0 commit comments

Comments
 (0)