Spiral Traversal of Matrix

This program prints elements of a matrix in spiral order.

Problem Statement

Write a Java program to print elements of a 3x3 matrix in spiral order.

Source Code

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

Program Output

Eduinq Matrix Spiral Traversal
1 2 3 6 9 8 7 4 5 

Explanation

Spiral traversal uses four boundaries: top, bottom, left, right. - Loops print top row, right column, bottom row, left column sequentially. - Boundaries shrink after each cycle. - Together demonstrates spiral traversal of matrix. Conclusion: Demonstrates spiral traversal of matrix using arrays.

Quick Links to Explore