diff --git a/src/main/java/MainExercises.java b/src/main/java/MainExercises.java index 763af45..60a5b89 100644 --- a/src/main/java/MainExercises.java +++ b/src/main/java/MainExercises.java @@ -65,10 +65,38 @@ 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 index = 0; + int top = 0, bottom = rows - 1; + int left = 0, right = cols - 1; + while (top <= bottom && left <= right) { + for (int j = left; j <= right; j++) { + result[index++] = matrix[top][j]; + } + top++; + for (int i = top; i <= bottom; i++) { + result[index++] = matrix[i][right]; + } + right--; + if (top <= bottom) { + for (int j = right; j >= left; j--) { + result[index++] = matrix[bottom][j]; + } + bottom--; + } + if (left <= right) { + for (int i = bottom; i >= top; i--) { + result[index++] = matrix[i][left]; + } + 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