Rotated Spiral Traversal

This program prints matrix elements in spiral order starting from bottom left corner.

Problem Statement

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

Source Code

1 public class RotatedSpiralTraversal {
2 public static void main(String[] args) {
3 System.out.println("Eduinq Rotated Spiral Traversal");
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=bottom;i>=top;i--) System.out.print(A[i][left]+" ");
13 left++;
14 for(int i=left;i<=right;i++) System.out.print(A[top][i]+" ");
15 top++;
16 for(int i=top;i<=bottom;i++) System.out.print(A[i][right]+" ");
17 right--;
18 for(int i=right;i>=left;i--) System.out.print(A[bottom][i]+" ");
19 bottom--;
20 }
21 }
22 }

Program Output

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

Explanation

The spiral traversal is rotated to start from the bottom-left corner by reordering which boundary is processed first, with the four boundaries still shrinking after each cycle, demonstrating a rotated variant of spiral traversal.

Quick Links to Explore