From b8b9b6f4828f92b80757b9ff47f875c90908f699 Mon Sep 17 00:00:00 2001 From: Fateme Azizi Date: Tue, 21 Apr 2026 22:37:05 +0330 Subject: [PATCH] implement spiralTraversal method --- src/main/java/MainExercises.java | 48 ++++++++++++++++++++++++++++++-- 1 file changed, 46 insertions(+), 2 deletions(-) diff --git a/src/main/java/MainExercises.java b/src/main/java/MainExercises.java index 598838a..e13066e 100644 --- a/src/main/java/MainExercises.java +++ b/src/main/java/MainExercises.java @@ -1,3 +1,5 @@ +import java.util.ArrayList; + public class MainExercises { /* @@ -69,8 +71,50 @@ public class MainExercises - Number of columns: matrix[0].length (if rectangular) */ public int[] spiralTraversal(int[][] matrix) { - // todo - return null; + + int rows = matrix.length; + int columns = matrix[0].length; + + int[] result = new int[rows*columns]; + int count = 0; + + int top = 0; + int bottom = rows - 1; + int right = columns - 1; + int left = 0; + + while (top <= bottom && left <= right) { + + for(int j = left ; j<=right ; j++) { + result[count] = matrix[top][j]; + count++; + } + top++; + + for(int i = top ; i<=bottom ; i++) { + result[count] = matrix[i][right]; + count++; + } + right--; + + if(top <= bottom) { + for (int j = right; j >= left; j--) { + result[count] = matrix[bottom][j]; + count++; + } + } + bottom--; + + if(left <= right){ + for (int i = bottom; i >= top; i--) { + result[count] = matrix[i][left]; + count++; + } + } + left++; + + } + return result; } /*