Reverse Spiral Traversal
This program prints matrix elements in reverse spiral order.
Problem Statement
Write a Java program to print elements of a 3x3 matrix in reverse spiral order.
Source Code
| 1 | public class ReverseSpiralTraversal { |
| 2 | public static void main(String[] args) { |
| 3 | System.out.println("Eduinq Reverse Spiral Traversal"); |
| 4 | int[][] A = {{1,2,3},{4,5,6},{7,8,9}}; |
| 5 | int[] spiral = new int[9]; |
| 6 | int top=0,bottom=2,left=0,right=2,index=0; |
| 7 | while(top<=bottom && left<=right){ |
| 8 | for(int i=left;i<=right;i++) spiral[index++]=A[top][i]; |
| 9 | top++; |
| 10 | for(int i=top;i<=bottom;i++) spiral[index++]=A[i][right]; |
| 11 | right--; |
| 12 | for(int i=right;i>=left;i--) spiral[index++]=A[bottom][i]; |
| 13 | bottom--; |
| 14 | for(int i=bottom;i>=top;i--) spiral[index++]=A[i][left]; |
| 15 | left++; |
| 16 | } |
| 17 | for(int i=spiral.length-1;i>=0;i--) System.out.print(spiral[i]+" "); |
| 18 | } |
| 19 | } |
Program Output
Eduinq Reverse Spiral Traversal 5 4 7 8 9 6 3 2 1
Explanation
The standard spiral order is first stored into a one-dimensional array using the usual boundary logic, and then that array is printed from the last index back to the first, together demonstrating reverse spiral traversal.