From 8fd66d9681108e1c46b8024a880fcd65e8a3f6da Mon Sep 17 00:00:00 2001 From: Mahdi HP Date: Thu, 23 Apr 2026 05:26:28 -0700 Subject: [PATCH] seconed question --- src/main/java/MainExercises.java | 50 ++++++++++++++++++++++++++++++-- 1 file changed, 48 insertions(+), 2 deletions(-) diff --git a/src/main/java/MainExercises.java b/src/main/java/MainExercises.java index 856145f..524c582 100644 --- a/src/main/java/MainExercises.java +++ b/src/main/java/MainExercises.java @@ -1,3 +1,5 @@ +import java.util.ArrayList; + public class MainExercises { /* @@ -71,11 +73,55 @@ public class MainExercises - Number of columns: matrix[0].length (if rectangular) */ - public int[] spiralTraversal(int[][] matrix) { - return null; + public int[] spiralTraversal(int[][] matrix) { + int rows = matrix.length; + int columns = matrix[0].length; + int[] result = new int[rows*columns]; + + int top = 0; + int down = rows-1; + int left = 0; + int right = columns-1; + int counter = 0; + + while(top <= down && left <= right){ + for (int i = left ; i <= right ; i++){ + result[counter] = matrix[top][i]; + counter++; + } + top++; + + for(int i = top ; i <= down ; i++){ + result[counter] = matrix[i][right]; + counter++; + } + right--; + + if (counter < rows*columns){ + for(int i = right ; i >= left ; i--){ + result[counter] = matrix[down][i]; + counter++; + } + down--; + + for(int i = down ; i >= top ; i--){ + result[counter]= matrix[i][left]; + counter++; + } + left++; + + + } + + } + + + + return result; } + /* integer partitioning is a combinatorics problem in discreet maths the problem is to generate sum numbers which their summation is the input number