Given a number n as the size of the matrix, the task is to print a spiral pattern in 2D array of size n.
Input: n = 5 Output: 1 2 3 4 5 16 17 18 19 6 15 24 25 20 7 14 23 22 21 8 13 12 11 10 9
Preview of the Spiral Pattern:
- Create a 2D array of size n
- Store the boundary of the array in boundary variable. Initially it will be n-1 and thereafter it changes after every rotation.
- Store the size left for the spiral printing in variable sizeLeft. Initially it will be n-1 and thereafter it will decrease by 1 after every 2 rotations.
- Create a flag to determine 2 rotations, as after every 2 rotations, the sizeLeft will decrease.
- Create a char variable move to store the current movement of the spiral pattern. It can have ‘r’ for right, ‘l’ for left, ‘d’ for down, and ‘u’ for up.
- Repeat the below steps till ‘i’ is in range [1, n^2]:
- Assign the value of i to the spiral pattern.
- Determine the next movement of the pattern.
- Check for pattern to reach boundary. If reached, modify the sizes and rotate the spiral pattern.
- Print the Spiral Pattern stored in the 2D array.
Below is Java implementation of the above approach:
1 2 3 4 5 16 17 18 19 6 15 24 25 20 7 14 23 22 21 8 13 12 11 10 9
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Spiral Pattern
- Print a given matrix in spiral form
- Print n x n spiral matrix using O(1) extra space
- Print K'th element in spiral form of matrix
- Print a given matrix in reverse spiral form
- Print a matrix in a spiral form starting from a point
- Print a given matrix in counter-clock wise spiral form
- Print a given matrix in spiral form using direction tracking method
- Program to print numbers with diamond pattern
- Java Program to Print a Square Pattern for given integer
- Program to Print the Trapezium Pattern
- Program to print Inverse Diamond pattern
- Program to print Hut Star pattern
- Program to print the pattern 1020304017018019020 **50607014015016 ****809012013 ******10011...
- Sum of both diagonals of a spiral odd-order square matrix
- Circular Matrix (Construct a matrix with numbers 1 to m*n in spiral way)
- Find the sum of the diagonal elements of the given N X N spiral matrix
- Form a Spiral Matrix from the given Array
- Convert given Matrix into sorted Spiral Matrix
- Print matrix in diagonal pattern
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.