1+ /*
2+ * Algorithm Name: Spiral Matrix Traversal
3+ * Programming Language: Java
4+ * Category: Matrix
5+ * Difficulty Level: Medium
6+ *
7+ * Author: Ojasvi Bakshi
8+ *
9+ * Algorithm Description:
10+ * Given an m x n matrix, return all elements of the matrix in spiral order.
11+ * The traversal starts from the top-left corner and moves layer by layer towards the center.
12+ *
13+ * Time Complexity: O(m*n) - Every element is visited exactly once.
14+ * Space Complexity: O(m*n) - To store the resulting list. O(1) if printing directly.
15+ */
16+
17+ import java .util .Scanner ;
18+ import java .util .ArrayList ;
19+ import java .util .List ;
20+ import java .util .Arrays ;
21+
22+ public class SpiralMatrixTraversal {
23+
24+ public static List <Integer > spiralOrder (int [][] matrix ) {
25+ List <Integer > result = new ArrayList <>();
26+ if (matrix == null || matrix .length == 0 ) {
27+ return result ;
28+ }
29+
30+ int m = matrix .length ;
31+ int n = matrix [0 ].length ;
32+ int top = 0 , bottom = m - 1 ;
33+ int left = 0 , right = n - 1 ;
34+
35+ while (top <= bottom && left <= right ) {
36+ // 1. Traverse Right on the top row
37+ for (int j = left ; j <= right ; j ++) {
38+ result .add (matrix [top ][j ]);
39+ }
40+ top ++;
41+
42+ // 2. Traverse Down on the right column
43+ for (int i = top ; i <= bottom ; i ++) {
44+ result .add (matrix [i ][right ]);
45+ }
46+ right --;
47+
48+ // 3. Traverse Left on the bottom row (check boundary)
49+ if (top <= bottom ) {
50+ for (int j = right ; j >= left ; j --) {
51+ result .add (matrix [bottom ][j ]);
52+ }
53+ bottom --;
54+ }
55+
56+ // 4. Traverse Up on the left column (check boundary)
57+ if (left <= right ) {
58+ for (int i = bottom ; i >= top ; i --) {
59+ result .add (matrix [i ][left ]);
60+ }
61+ left ++;
62+ }
63+ }
64+ return result ;
65+ }
66+
67+ public static void main (String [] args ) {
68+ Scanner sc = new Scanner (System .in );
69+
70+ System .out .print ("Enter number of rows: " );
71+ int m = sc .nextInt ();
72+ System .out .print ("Enter number of columns: " );
73+ int n = sc .nextInt ();
74+
75+ int [][] matrix = new int [m ][n ];
76+
77+ System .out .println ("Enter matrix elements:" );
78+ for (int i = 0 ; i < m ; i ++) {
79+ for (int j = 0 ; j < n ; j ++) {
80+ matrix [i ][j ] = sc .nextInt ();
81+ }
82+ }
83+
84+ System .out .println ("\n Original Matrix:" );
85+ for (int [] row : matrix ) {
86+ System .out .println (Arrays .toString (row ));
87+ }
88+
89+ // Apply the algorithm
90+ List <Integer > spiral = spiralOrder (matrix );
91+
92+ System .out .println ("\n Matrix in Spiral Order:" );
93+ System .out .println (spiral );
94+
95+ sc .close ();
96+ }
97+ }
0 commit comments