From c59b80f87c544f69799202863d05686dcb5f5370 Mon Sep 17 00:00:00 2001 From: Matin-Ardestani Date: Tue, 21 Apr 2026 17:12:50 +0330 Subject: [PATCH] Implement Traversal method --- src/main/java/MainExercises.java | 44 ++++++++++++++++++++++++++++++-- 1 file changed, 42 insertions(+), 2 deletions(-) diff --git a/src/main/java/MainExercises.java b/src/main/java/MainExercises.java index b2d063d..2d9b518 100644 --- a/src/main/java/MainExercises.java +++ b/src/main/java/MainExercises.java @@ -72,8 +72,48 @@ public class MainExercises - Number of columns: matrix[0].length (if rectangular) */ public int[] spiralTraversal(int[][] matrix) { - // todo - return null; + + int rows = matrix.length; + int cols = matrix[0].length; + + int[] result = new int[rows * cols]; + + int top = 0, bottom = rows - 1, left = 0, right = cols - 1; + int id = 0; + + while(top <= bottom && left <= right){ // reaching the center + + for(int col = left; col <= right; col++){ + result[id] = matrix[top][col]; + id++; + } + top++; + + for(int row = top; row <= bottom; row++){ + result[id] = matrix[row][right]; + id++; + } + right--; + + if(top <= right){ + for(int col = right; col >= left; col--){ + result[id] = matrix[bottom][col]; + id++; + } + bottom--; + } + + if(left <= right){ + for(int row = bottom; row >= top; row--){ + result[id] = matrix[row][left]; + id++; + } + left++; + } + + } + + return result; } /*