package org.wesome.dsalgo;
import java.util.Objects;
public class PrintSpiralMatrix {
public static void printSpiralMatrix(int[][] matrix, int top, int bottom, int left, int right) {
// base case
if (Objects.isNull(matrix) || matrix.length == 0 || left > right) {
return;
}
/* print top row */
for (int i = left; i <= right; i++) {
System.out.print(matrix[top][i] + " ");
}
/* increment the top, for next iteration current top + 1 will be new top */
top++;
if (top > bottom) {
return;
}
/* print right column */
for (int i = top; i <= bottom; i++) {
System.out.print(matrix[i][right] + " ");
}
/* decrement the right, for next iteration current right - 1 will be new right */
right--;
if (left > right) {
return;
}
/* print bottom row */
for (int i = right; i >= left; i--) {
System.out.print(matrix[bottom][i] + " ");
}
/* decrement the bottom, for next iteration current bottom - 1 will be new bottom */
bottom--;
if (top > bottom) {
return;
}
/* print left row */
for (int i = bottom; i >= top; i--) {
System.out.print(matrix[i][left] + " ");
}
/* increment the left, for next iteration current left + 1 will be new left */
left++;
printSpiralMatrix(matrix, top, bottom, left, right);
}
}
package org.wesome.dsalgo;
import org.junit.jupiter.api.Test;
public class PrintSpiralMatrixTest {
@Test
public void sortArrayWithDuplicateTest() {
int[][] mat = {{1, 2, 3, 4, 5},
{16, 17, 18, 19, 6},
{15, 24, 25, 20, 7},
{14, 23, 22, 21, 8},
{13, 12, 11, 10, 9}};
int top = 0, bottom = mat.length - 1;
int left = 0, right = mat[0].length - 1;
PrintSpiralMatrix.printSpiralMatrix(mat, top, bottom, left, right);
}
}
plugins {
id 'java'
id "io.freefair.lombok" version "6.2.0"
}
group = 'org.wesome'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = JavaVersion.VERSION_1_8
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
}
dependencies {
testImplementation 'org.junit.jupiter:junit-jupiter:5.6.2'
}
test {
useJUnitPlatform()
}