diff --git a/src/main/java/com/thealgorithms/matrix/SpiralMatrixII.java b/src/main/java/com/thealgorithms/matrix/SpiralMatrixII.java new file mode 100644 index 000000000000..bb8e36490ccf --- /dev/null +++ b/src/main/java/com/thealgorithms/matrix/SpiralMatrixII.java @@ -0,0 +1,53 @@ +/** + * Spiral Matrix II + * Generates an n x n matrix filled with numbers from 1 to n^2 in spiral order. + * + * @see LeetCode – Spiral Matrix II + * @see Wikipedia – Spiral Matrix + */ +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; + } +} diff --git a/src/test/java/com/thealgorithms/matrix/SpiralMatrixIITest.java b/src/test/java/com/thealgorithms/matrix/SpiralMatrixIITest.java new file mode 100644 index 000000000000..265752b37577 --- /dev/null +++ b/src/test/java/com/thealgorithms/matrix/SpiralMatrixIITest.java @@ -0,0 +1,26 @@ +package com.thealgorithms.matrix; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import org.junit.jupiter.api.Test; + +class SpiralMatrixTest { + + SpiralMatrix spiral = new SpiralMatrix(); + + @Test + void testNEquals3() { + int[][] expected = {{1, 2, 3}, {8, 9, 4}, {7, 6, 5}}; + assertArrayEquals(expected, spiral.generateMatrix(3)); + } + + @Test + void testNEquals4() { + int[][] expected = {{1, 2, 3, 4}, {12, 13, 14, 5}, {11, 16, 15, 6}, {10, 9, 8, 7}}; + assertArrayEquals(expected, spiral.generateMatrix(4)); + } + + @Test + void testNEquals2() { + int[][] expected = {{1, 2}, {4, 3}}; + assertArrayEquals(expected, spiral.generateMatrix(2)); + } +}