File tree Expand file tree Collapse file tree 2 files changed +80
-0
lines changed
main/java/com/thealgorithms/matrix
test/java/com/thealgorithms/matrix Expand file tree Collapse file tree 2 files changed +80
-0
lines changed Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments