Spiral Traversal Extended

This program prints elements of a 4x4 matrix in spiral order.

Problem Statement

Write a Java program to print elements of a 4x4 matrix in spiral order.

Source Code

1 public class MatrixSpiralTraversalExtended {
2 public static void main(String[] args) {
3 System.out.println("Eduinq Matrix Spiral Traversal Extended");
4 int[][] A = {
5 {1,2,3,4},
6 {5,6,7,8},
7 {9,10,11,12},
8 {13,14,15,16}
9 };
10 int top=0, bottom=3, left=0, right=3;
11 while(top<=bottom && left<=right){
12 for(int i=left;i<=right;i++) System.out.print(A[top][i]+" ");
13 top++;
14 for(int i=top;i<=bottom;i++) System.out.print(A[i][right]+" ");
15 right--;
16 for(int i=right;i>=left;i--) System.out.print(A[bottom][i]+" ");
17 bottom--;
18 for(int i=bottom;i>=top;i--) System.out.print(A[i][left]+" ");
19 left++;
20 }
21 }
22 }

Program Output

Eduinq Matrix Spiral Traversal Extended
1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10 

Explanation

The same spiral traversal boundary logic is applied to a larger 4x4 matrix, with the four boundaries shrinking after every layer, demonstrating that spiral traversal generalizes naturally to bigger matrices.

Quick Links to Explore