Java program for printing the matrix elements in Spiral Order – Full Explanation

Given 2D Matrix

1 2 3

4 5 6

7 8 9

Explanation

Spiral Matrix

Step 1: Print the values from first row.

row = 3 & column = 3

1 2 3
4 5 6
7 8 9

Step 2: Print the last column from top to bottom.

row = 2 & column = 3

4 5 6
7 8 9

Step 3: Print the last row by from right to left.

row = 2 & column = 2

4 5
7 8

Step 4: Print the first column bottom to top.

row = 1 & column = 2

4 5

Step 5: Again print the first row. i.e middle row

Print the middle row.

row = 1 & column = 1

5

Java Program

Sample Output

1
2
3
6
9
8
7
4
5

Quick Info:

  • It is non-regressive function.
  • Time Complexity O(n^2)
  • Space Complexity O(1)

This is one of the important interview questions 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.